file_id
stringlengths 4
10
| content
stringlengths 91
42.8k
| repo
stringlengths 7
108
| path
stringlengths 7
251
| token_length
int64 34
8.19k
| original_comment
stringlengths 11
11.5k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 34
42.8k
|
---|---|---|---|---|---|---|---|---|
209255_3 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service.impl.mapper.strategie;
import java.sql.Timestamp;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.AdministratieveHandeling;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.BRPActie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Entiteit;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.FormeleHistorieZonderVerantwoording;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Onderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.OnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Persoon;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Relatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.RelatieHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortActie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortRelatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.StatusOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpAttribuutMetOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpDatum;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpNaamgebruikGeslachtsnaamstam;
import nl.bzk.migratiebrp.conversie.model.lo3.element.Lo3Onderzoek;
/**
* Mapper om op algemene wijze een onderzoek op gegevens te vertalen naar BRP entiteiten.
*/
public final class OnderzoekMapperImpl implements OnderzoekMapper {
/**
* Prefix string die wordt gebruikt in de omschrijving van een onderzoek dat uit LO3 is geconverteerd.
*/
public static final String LO3_ONDERZOEK_OMSCHRIJVING_PREFIX = "Conversie GBA: ";
private final Map<Lo3Onderzoek, Onderzoek> onderzoekMap = new IdentityHashMap<>();
private final Persoon persoon;
private final Partij partij;
/**
* Constructor voor de onderzoek mapper waarbij de persoon wordt meegegeven waaraan het onderzoek gekoppeld gaat
* worden.
* @param persoon de persoon waaraan het onderzoek gekoppeld gaat worden
* @param partij de partij
*/
public OnderzoekMapperImpl(final Persoon persoon, final Partij partij) {
this.persoon = persoon;
this.partij = partij;
}
@Override
public Set<Onderzoek> getOnderzoekSet() {
return new LinkedHashSet<>(onderzoekMap.values());
}
@Override
public void mapOnderzoek(final Entiteit deltaEntiteit, final BrpAttribuutMetOnderzoek attribuut, final Element soortGegeven) {
if (soortGegeven != null && attribuut != null && attribuut.isInhoudelijkGevuld()) {
mapOnderzoek(deltaEntiteit, soortGegeven, attribuut.getOnderzoek());
}
}
private void mapOnderzoek(final Entiteit deltaEntiteit, final Element soortGegeven, final Lo3Onderzoek lo3Onderzoek) {
if (lo3Onderzoek != null) {
final Onderzoek onderzoek;
if (!onderzoekMap.containsKey(lo3Onderzoek)) {
onderzoek = maakOnderzoek(lo3Onderzoek);
onderzoekMap.put(lo3Onderzoek, onderzoek);
} else {
onderzoek = onderzoekMap.get(lo3Onderzoek);
}
// Onderzoek op tsreg van RelatieHistorie hoeft bij FRB niet gedaan te worden.
if (!isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(deltaEntiteit, soortGegeven)) {
final GegevenInOnderzoek gegevenInOnderzoek = new GegevenInOnderzoek(onderzoek, soortGegeven);
final GegevenInOnderzoekHistorie
gegevenInOnderzoekHistorie =
new GegevenInOnderzoekHistorie(gegevenInOnderzoek, onderzoek.getOnderzoekHistorieSet().iterator().next().getActieInhoud());
gegevenInOnderzoek.addGegevenInOnderzoekHistorie(gegevenInOnderzoekHistorie);
gegevenInOnderzoek.setEntiteitOfVoorkomen(deltaEntiteit);
if (!bevatGelijkGegeven(onderzoek.getGegevenInOnderzoekSet(), gegevenInOnderzoek)) {
onderzoek.addGegevenInOnderzoek(gegevenInOnderzoek);
}
}
}
}
private boolean isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(final Entiteit deltaEntiteit, final Element soortGegeven) {
boolean result = false;
if (deltaEntiteit instanceof RelatieHistorie) {
final Relatie relatie = ((RelatieHistorie) deltaEntiteit).getRelatie();
result = SoortRelatie.FAMILIERECHTELIJKE_BETREKKING.equals(relatie.getSoortRelatie()) && Element.RELATIE_TIJDSTIPREGISTRATIE.equals
(soortGegeven);
}
return result;
}
@Override
public void mapOnderzoeken(final Entiteit entiteit, final BrpNaamgebruikGeslachtsnaamstam naamgebruikGeslachtsnaamstam, final Element soortGegeven) {
if (naamgebruikGeslachtsnaamstam == null || naamgebruikGeslachtsnaamstam.getOnderzoeken() == null) {
return;
}
for (final Lo3Onderzoek lo3Onderzoek : naamgebruikGeslachtsnaamstam.getOnderzoeken()) {
mapOnderzoek(entiteit, soortGegeven, lo3Onderzoek);
}
}
private boolean bevatGelijkGegeven(final Set<GegevenInOnderzoek> gegevenInOnderzoekSet, final GegevenInOnderzoek gegevenInOnderzoek) {
for (final GegevenInOnderzoek gegevenInSet : gegevenInOnderzoekSet) {
if (gegevenInSet.getEntiteitOfVoorkomen() == gegevenInOnderzoek.getEntiteitOfVoorkomen()
&& gegevenInSet.getSoortGegeven() == gegevenInOnderzoek.getSoortGegeven()) {
return true;
}
}
return false;
}
private Onderzoek maakOnderzoek(final Lo3Onderzoek lo3Onderzoek) {
final BRPActie actie = maakBrpActie();
final Onderzoek onderzoek = new Onderzoek(partij, persoon);
persoon.addOnderzoek(onderzoek);
onderzoek.setVoortgekomenUitNietActueelVoorkomen(lo3Onderzoek.getLo3Herkomst() == null || !lo3Onderzoek.getLo3Herkomst().isLo3ActueelVoorkomen());
final Integer datumAanvang = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumIngangOnderzoek()).getWaarde();
final StatusOnderzoek statusOnderzoek;
final Integer datumEinde;
if (lo3Onderzoek.getDatumEindeOnderzoek() != null) {
datumEinde = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumEindeOnderzoek()).getWaarde();
statusOnderzoek = StatusOnderzoek.AFGESLOTEN;
} else {
datumEinde = null;
statusOnderzoek = StatusOnderzoek.IN_UITVOERING;
}
final OnderzoekHistorie historie = new OnderzoekHistorie(datumAanvang, statusOnderzoek, onderzoek);
historie.setOmschrijving(LO3_ONDERZOEK_OMSCHRIJVING_PREFIX + lo3Onderzoek.getAanduidingGegevensInOnderzoekCode());
historie.setDatumTijdRegistratie(actie.getDatumTijdRegistratie());
historie.setDatumEinde(datumEinde);
historie.setActieInhoud(actie);
onderzoek.addOnderzoekHistorie(historie);
return onderzoek;
}
private BRPActie maakBrpActie() {
final AdministratieveHandeling administratieveHandeling = getAdministratieveHandeling();
final Timestamp datumtijdstempel =
FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonInschrijvingHistorieSet()).getDatumtijdstempel();
return new BRPActie(SoortActie.CONVERSIE_GBA, administratieveHandeling, administratieveHandeling.getPartij(), datumtijdstempel);
}
private AdministratieveHandeling getAdministratieveHandeling() {
return FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonAfgeleidAdministratiefHistorieSet())
.getAdministratieveHandeling();
}
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-synchronisatie-dal/src/main/java/nl/bzk/migratiebrp/synchronisatie/dal/service/impl/mapper/strategie/OnderzoekMapperImpl.java | 2,386 | /**
* Constructor voor de onderzoek mapper waarbij de persoon wordt meegegeven waaraan het onderzoek gekoppeld gaat
* worden.
* @param persoon de persoon waaraan het onderzoek gekoppeld gaat worden
* @param partij de partij
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service.impl.mapper.strategie;
import java.sql.Timestamp;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.AdministratieveHandeling;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.BRPActie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Entiteit;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.FormeleHistorieZonderVerantwoording;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Onderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.OnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Persoon;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Relatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.RelatieHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortActie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortRelatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.StatusOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpAttribuutMetOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpDatum;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpNaamgebruikGeslachtsnaamstam;
import nl.bzk.migratiebrp.conversie.model.lo3.element.Lo3Onderzoek;
/**
* Mapper om op algemene wijze een onderzoek op gegevens te vertalen naar BRP entiteiten.
*/
public final class OnderzoekMapperImpl implements OnderzoekMapper {
/**
* Prefix string die wordt gebruikt in de omschrijving van een onderzoek dat uit LO3 is geconverteerd.
*/
public static final String LO3_ONDERZOEK_OMSCHRIJVING_PREFIX = "Conversie GBA: ";
private final Map<Lo3Onderzoek, Onderzoek> onderzoekMap = new IdentityHashMap<>();
private final Persoon persoon;
private final Partij partij;
/**
* Constructor voor de<SUF>*/
public OnderzoekMapperImpl(final Persoon persoon, final Partij partij) {
this.persoon = persoon;
this.partij = partij;
}
@Override
public Set<Onderzoek> getOnderzoekSet() {
return new LinkedHashSet<>(onderzoekMap.values());
}
@Override
public void mapOnderzoek(final Entiteit deltaEntiteit, final BrpAttribuutMetOnderzoek attribuut, final Element soortGegeven) {
if (soortGegeven != null && attribuut != null && attribuut.isInhoudelijkGevuld()) {
mapOnderzoek(deltaEntiteit, soortGegeven, attribuut.getOnderzoek());
}
}
private void mapOnderzoek(final Entiteit deltaEntiteit, final Element soortGegeven, final Lo3Onderzoek lo3Onderzoek) {
if (lo3Onderzoek != null) {
final Onderzoek onderzoek;
if (!onderzoekMap.containsKey(lo3Onderzoek)) {
onderzoek = maakOnderzoek(lo3Onderzoek);
onderzoekMap.put(lo3Onderzoek, onderzoek);
} else {
onderzoek = onderzoekMap.get(lo3Onderzoek);
}
// Onderzoek op tsreg van RelatieHistorie hoeft bij FRB niet gedaan te worden.
if (!isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(deltaEntiteit, soortGegeven)) {
final GegevenInOnderzoek gegevenInOnderzoek = new GegevenInOnderzoek(onderzoek, soortGegeven);
final GegevenInOnderzoekHistorie
gegevenInOnderzoekHistorie =
new GegevenInOnderzoekHistorie(gegevenInOnderzoek, onderzoek.getOnderzoekHistorieSet().iterator().next().getActieInhoud());
gegevenInOnderzoek.addGegevenInOnderzoekHistorie(gegevenInOnderzoekHistorie);
gegevenInOnderzoek.setEntiteitOfVoorkomen(deltaEntiteit);
if (!bevatGelijkGegeven(onderzoek.getGegevenInOnderzoekSet(), gegevenInOnderzoek)) {
onderzoek.addGegevenInOnderzoek(gegevenInOnderzoek);
}
}
}
}
private boolean isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(final Entiteit deltaEntiteit, final Element soortGegeven) {
boolean result = false;
if (deltaEntiteit instanceof RelatieHistorie) {
final Relatie relatie = ((RelatieHistorie) deltaEntiteit).getRelatie();
result = SoortRelatie.FAMILIERECHTELIJKE_BETREKKING.equals(relatie.getSoortRelatie()) && Element.RELATIE_TIJDSTIPREGISTRATIE.equals
(soortGegeven);
}
return result;
}
@Override
public void mapOnderzoeken(final Entiteit entiteit, final BrpNaamgebruikGeslachtsnaamstam naamgebruikGeslachtsnaamstam, final Element soortGegeven) {
if (naamgebruikGeslachtsnaamstam == null || naamgebruikGeslachtsnaamstam.getOnderzoeken() == null) {
return;
}
for (final Lo3Onderzoek lo3Onderzoek : naamgebruikGeslachtsnaamstam.getOnderzoeken()) {
mapOnderzoek(entiteit, soortGegeven, lo3Onderzoek);
}
}
private boolean bevatGelijkGegeven(final Set<GegevenInOnderzoek> gegevenInOnderzoekSet, final GegevenInOnderzoek gegevenInOnderzoek) {
for (final GegevenInOnderzoek gegevenInSet : gegevenInOnderzoekSet) {
if (gegevenInSet.getEntiteitOfVoorkomen() == gegevenInOnderzoek.getEntiteitOfVoorkomen()
&& gegevenInSet.getSoortGegeven() == gegevenInOnderzoek.getSoortGegeven()) {
return true;
}
}
return false;
}
private Onderzoek maakOnderzoek(final Lo3Onderzoek lo3Onderzoek) {
final BRPActie actie = maakBrpActie();
final Onderzoek onderzoek = new Onderzoek(partij, persoon);
persoon.addOnderzoek(onderzoek);
onderzoek.setVoortgekomenUitNietActueelVoorkomen(lo3Onderzoek.getLo3Herkomst() == null || !lo3Onderzoek.getLo3Herkomst().isLo3ActueelVoorkomen());
final Integer datumAanvang = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumIngangOnderzoek()).getWaarde();
final StatusOnderzoek statusOnderzoek;
final Integer datumEinde;
if (lo3Onderzoek.getDatumEindeOnderzoek() != null) {
datumEinde = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumEindeOnderzoek()).getWaarde();
statusOnderzoek = StatusOnderzoek.AFGESLOTEN;
} else {
datumEinde = null;
statusOnderzoek = StatusOnderzoek.IN_UITVOERING;
}
final OnderzoekHistorie historie = new OnderzoekHistorie(datumAanvang, statusOnderzoek, onderzoek);
historie.setOmschrijving(LO3_ONDERZOEK_OMSCHRIJVING_PREFIX + lo3Onderzoek.getAanduidingGegevensInOnderzoekCode());
historie.setDatumTijdRegistratie(actie.getDatumTijdRegistratie());
historie.setDatumEinde(datumEinde);
historie.setActieInhoud(actie);
onderzoek.addOnderzoekHistorie(historie);
return onderzoek;
}
private BRPActie maakBrpActie() {
final AdministratieveHandeling administratieveHandeling = getAdministratieveHandeling();
final Timestamp datumtijdstempel =
FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonInschrijvingHistorieSet()).getDatumtijdstempel();
return new BRPActie(SoortActie.CONVERSIE_GBA, administratieveHandeling, administratieveHandeling.getPartij(), datumtijdstempel);
}
private AdministratieveHandeling getAdministratieveHandeling() {
return FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonAfgeleidAdministratiefHistorieSet())
.getAdministratieveHandeling();
}
}
|
209255_4 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service.impl.mapper.strategie;
import java.sql.Timestamp;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.AdministratieveHandeling;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.BRPActie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Entiteit;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.FormeleHistorieZonderVerantwoording;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Onderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.OnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Persoon;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Relatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.RelatieHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortActie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortRelatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.StatusOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpAttribuutMetOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpDatum;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpNaamgebruikGeslachtsnaamstam;
import nl.bzk.migratiebrp.conversie.model.lo3.element.Lo3Onderzoek;
/**
* Mapper om op algemene wijze een onderzoek op gegevens te vertalen naar BRP entiteiten.
*/
public final class OnderzoekMapperImpl implements OnderzoekMapper {
/**
* Prefix string die wordt gebruikt in de omschrijving van een onderzoek dat uit LO3 is geconverteerd.
*/
public static final String LO3_ONDERZOEK_OMSCHRIJVING_PREFIX = "Conversie GBA: ";
private final Map<Lo3Onderzoek, Onderzoek> onderzoekMap = new IdentityHashMap<>();
private final Persoon persoon;
private final Partij partij;
/**
* Constructor voor de onderzoek mapper waarbij de persoon wordt meegegeven waaraan het onderzoek gekoppeld gaat
* worden.
* @param persoon de persoon waaraan het onderzoek gekoppeld gaat worden
* @param partij de partij
*/
public OnderzoekMapperImpl(final Persoon persoon, final Partij partij) {
this.persoon = persoon;
this.partij = partij;
}
@Override
public Set<Onderzoek> getOnderzoekSet() {
return new LinkedHashSet<>(onderzoekMap.values());
}
@Override
public void mapOnderzoek(final Entiteit deltaEntiteit, final BrpAttribuutMetOnderzoek attribuut, final Element soortGegeven) {
if (soortGegeven != null && attribuut != null && attribuut.isInhoudelijkGevuld()) {
mapOnderzoek(deltaEntiteit, soortGegeven, attribuut.getOnderzoek());
}
}
private void mapOnderzoek(final Entiteit deltaEntiteit, final Element soortGegeven, final Lo3Onderzoek lo3Onderzoek) {
if (lo3Onderzoek != null) {
final Onderzoek onderzoek;
if (!onderzoekMap.containsKey(lo3Onderzoek)) {
onderzoek = maakOnderzoek(lo3Onderzoek);
onderzoekMap.put(lo3Onderzoek, onderzoek);
} else {
onderzoek = onderzoekMap.get(lo3Onderzoek);
}
// Onderzoek op tsreg van RelatieHistorie hoeft bij FRB niet gedaan te worden.
if (!isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(deltaEntiteit, soortGegeven)) {
final GegevenInOnderzoek gegevenInOnderzoek = new GegevenInOnderzoek(onderzoek, soortGegeven);
final GegevenInOnderzoekHistorie
gegevenInOnderzoekHistorie =
new GegevenInOnderzoekHistorie(gegevenInOnderzoek, onderzoek.getOnderzoekHistorieSet().iterator().next().getActieInhoud());
gegevenInOnderzoek.addGegevenInOnderzoekHistorie(gegevenInOnderzoekHistorie);
gegevenInOnderzoek.setEntiteitOfVoorkomen(deltaEntiteit);
if (!bevatGelijkGegeven(onderzoek.getGegevenInOnderzoekSet(), gegevenInOnderzoek)) {
onderzoek.addGegevenInOnderzoek(gegevenInOnderzoek);
}
}
}
}
private boolean isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(final Entiteit deltaEntiteit, final Element soortGegeven) {
boolean result = false;
if (deltaEntiteit instanceof RelatieHistorie) {
final Relatie relatie = ((RelatieHistorie) deltaEntiteit).getRelatie();
result = SoortRelatie.FAMILIERECHTELIJKE_BETREKKING.equals(relatie.getSoortRelatie()) && Element.RELATIE_TIJDSTIPREGISTRATIE.equals
(soortGegeven);
}
return result;
}
@Override
public void mapOnderzoeken(final Entiteit entiteit, final BrpNaamgebruikGeslachtsnaamstam naamgebruikGeslachtsnaamstam, final Element soortGegeven) {
if (naamgebruikGeslachtsnaamstam == null || naamgebruikGeslachtsnaamstam.getOnderzoeken() == null) {
return;
}
for (final Lo3Onderzoek lo3Onderzoek : naamgebruikGeslachtsnaamstam.getOnderzoeken()) {
mapOnderzoek(entiteit, soortGegeven, lo3Onderzoek);
}
}
private boolean bevatGelijkGegeven(final Set<GegevenInOnderzoek> gegevenInOnderzoekSet, final GegevenInOnderzoek gegevenInOnderzoek) {
for (final GegevenInOnderzoek gegevenInSet : gegevenInOnderzoekSet) {
if (gegevenInSet.getEntiteitOfVoorkomen() == gegevenInOnderzoek.getEntiteitOfVoorkomen()
&& gegevenInSet.getSoortGegeven() == gegevenInOnderzoek.getSoortGegeven()) {
return true;
}
}
return false;
}
private Onderzoek maakOnderzoek(final Lo3Onderzoek lo3Onderzoek) {
final BRPActie actie = maakBrpActie();
final Onderzoek onderzoek = new Onderzoek(partij, persoon);
persoon.addOnderzoek(onderzoek);
onderzoek.setVoortgekomenUitNietActueelVoorkomen(lo3Onderzoek.getLo3Herkomst() == null || !lo3Onderzoek.getLo3Herkomst().isLo3ActueelVoorkomen());
final Integer datumAanvang = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumIngangOnderzoek()).getWaarde();
final StatusOnderzoek statusOnderzoek;
final Integer datumEinde;
if (lo3Onderzoek.getDatumEindeOnderzoek() != null) {
datumEinde = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumEindeOnderzoek()).getWaarde();
statusOnderzoek = StatusOnderzoek.AFGESLOTEN;
} else {
datumEinde = null;
statusOnderzoek = StatusOnderzoek.IN_UITVOERING;
}
final OnderzoekHistorie historie = new OnderzoekHistorie(datumAanvang, statusOnderzoek, onderzoek);
historie.setOmschrijving(LO3_ONDERZOEK_OMSCHRIJVING_PREFIX + lo3Onderzoek.getAanduidingGegevensInOnderzoekCode());
historie.setDatumTijdRegistratie(actie.getDatumTijdRegistratie());
historie.setDatumEinde(datumEinde);
historie.setActieInhoud(actie);
onderzoek.addOnderzoekHistorie(historie);
return onderzoek;
}
private BRPActie maakBrpActie() {
final AdministratieveHandeling administratieveHandeling = getAdministratieveHandeling();
final Timestamp datumtijdstempel =
FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonInschrijvingHistorieSet()).getDatumtijdstempel();
return new BRPActie(SoortActie.CONVERSIE_GBA, administratieveHandeling, administratieveHandeling.getPartij(), datumtijdstempel);
}
private AdministratieveHandeling getAdministratieveHandeling() {
return FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonAfgeleidAdministratiefHistorieSet())
.getAdministratieveHandeling();
}
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-synchronisatie-dal/src/main/java/nl/bzk/migratiebrp/synchronisatie/dal/service/impl/mapper/strategie/OnderzoekMapperImpl.java | 2,386 | // Onderzoek op tsreg van RelatieHistorie hoeft bij FRB niet gedaan te worden. | line_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service.impl.mapper.strategie;
import java.sql.Timestamp;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.AdministratieveHandeling;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.BRPActie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Entiteit;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.FormeleHistorieZonderVerantwoording;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.GegevenInOnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Onderzoek;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.OnderzoekHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Persoon;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Relatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.RelatieHistorie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortActie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortRelatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.StatusOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpAttribuutMetOnderzoek;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpDatum;
import nl.bzk.migratiebrp.conversie.model.brp.attribuut.BrpNaamgebruikGeslachtsnaamstam;
import nl.bzk.migratiebrp.conversie.model.lo3.element.Lo3Onderzoek;
/**
* Mapper om op algemene wijze een onderzoek op gegevens te vertalen naar BRP entiteiten.
*/
public final class OnderzoekMapperImpl implements OnderzoekMapper {
/**
* Prefix string die wordt gebruikt in de omschrijving van een onderzoek dat uit LO3 is geconverteerd.
*/
public static final String LO3_ONDERZOEK_OMSCHRIJVING_PREFIX = "Conversie GBA: ";
private final Map<Lo3Onderzoek, Onderzoek> onderzoekMap = new IdentityHashMap<>();
private final Persoon persoon;
private final Partij partij;
/**
* Constructor voor de onderzoek mapper waarbij de persoon wordt meegegeven waaraan het onderzoek gekoppeld gaat
* worden.
* @param persoon de persoon waaraan het onderzoek gekoppeld gaat worden
* @param partij de partij
*/
public OnderzoekMapperImpl(final Persoon persoon, final Partij partij) {
this.persoon = persoon;
this.partij = partij;
}
@Override
public Set<Onderzoek> getOnderzoekSet() {
return new LinkedHashSet<>(onderzoekMap.values());
}
@Override
public void mapOnderzoek(final Entiteit deltaEntiteit, final BrpAttribuutMetOnderzoek attribuut, final Element soortGegeven) {
if (soortGegeven != null && attribuut != null && attribuut.isInhoudelijkGevuld()) {
mapOnderzoek(deltaEntiteit, soortGegeven, attribuut.getOnderzoek());
}
}
private void mapOnderzoek(final Entiteit deltaEntiteit, final Element soortGegeven, final Lo3Onderzoek lo3Onderzoek) {
if (lo3Onderzoek != null) {
final Onderzoek onderzoek;
if (!onderzoekMap.containsKey(lo3Onderzoek)) {
onderzoek = maakOnderzoek(lo3Onderzoek);
onderzoekMap.put(lo3Onderzoek, onderzoek);
} else {
onderzoek = onderzoekMap.get(lo3Onderzoek);
}
// Onderzoek op<SUF>
if (!isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(deltaEntiteit, soortGegeven)) {
final GegevenInOnderzoek gegevenInOnderzoek = new GegevenInOnderzoek(onderzoek, soortGegeven);
final GegevenInOnderzoekHistorie
gegevenInOnderzoekHistorie =
new GegevenInOnderzoekHistorie(gegevenInOnderzoek, onderzoek.getOnderzoekHistorieSet().iterator().next().getActieInhoud());
gegevenInOnderzoek.addGegevenInOnderzoekHistorie(gegevenInOnderzoekHistorie);
gegevenInOnderzoek.setEntiteitOfVoorkomen(deltaEntiteit);
if (!bevatGelijkGegeven(onderzoek.getGegevenInOnderzoekSet(), gegevenInOnderzoek)) {
onderzoek.addGegevenInOnderzoek(gegevenInOnderzoek);
}
}
}
}
private boolean isEntiteitEenRelatieHistorieEnSoortGegevenTijdstipRegistratie(final Entiteit deltaEntiteit, final Element soortGegeven) {
boolean result = false;
if (deltaEntiteit instanceof RelatieHistorie) {
final Relatie relatie = ((RelatieHistorie) deltaEntiteit).getRelatie();
result = SoortRelatie.FAMILIERECHTELIJKE_BETREKKING.equals(relatie.getSoortRelatie()) && Element.RELATIE_TIJDSTIPREGISTRATIE.equals
(soortGegeven);
}
return result;
}
@Override
public void mapOnderzoeken(final Entiteit entiteit, final BrpNaamgebruikGeslachtsnaamstam naamgebruikGeslachtsnaamstam, final Element soortGegeven) {
if (naamgebruikGeslachtsnaamstam == null || naamgebruikGeslachtsnaamstam.getOnderzoeken() == null) {
return;
}
for (final Lo3Onderzoek lo3Onderzoek : naamgebruikGeslachtsnaamstam.getOnderzoeken()) {
mapOnderzoek(entiteit, soortGegeven, lo3Onderzoek);
}
}
private boolean bevatGelijkGegeven(final Set<GegevenInOnderzoek> gegevenInOnderzoekSet, final GegevenInOnderzoek gegevenInOnderzoek) {
for (final GegevenInOnderzoek gegevenInSet : gegevenInOnderzoekSet) {
if (gegevenInSet.getEntiteitOfVoorkomen() == gegevenInOnderzoek.getEntiteitOfVoorkomen()
&& gegevenInSet.getSoortGegeven() == gegevenInOnderzoek.getSoortGegeven()) {
return true;
}
}
return false;
}
private Onderzoek maakOnderzoek(final Lo3Onderzoek lo3Onderzoek) {
final BRPActie actie = maakBrpActie();
final Onderzoek onderzoek = new Onderzoek(partij, persoon);
persoon.addOnderzoek(onderzoek);
onderzoek.setVoortgekomenUitNietActueelVoorkomen(lo3Onderzoek.getLo3Herkomst() == null || !lo3Onderzoek.getLo3Herkomst().isLo3ActueelVoorkomen());
final Integer datumAanvang = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumIngangOnderzoek()).getWaarde();
final StatusOnderzoek statusOnderzoek;
final Integer datumEinde;
if (lo3Onderzoek.getDatumEindeOnderzoek() != null) {
datumEinde = BrpDatum.fromLo3Datum(lo3Onderzoek.getDatumEindeOnderzoek()).getWaarde();
statusOnderzoek = StatusOnderzoek.AFGESLOTEN;
} else {
datumEinde = null;
statusOnderzoek = StatusOnderzoek.IN_UITVOERING;
}
final OnderzoekHistorie historie = new OnderzoekHistorie(datumAanvang, statusOnderzoek, onderzoek);
historie.setOmschrijving(LO3_ONDERZOEK_OMSCHRIJVING_PREFIX + lo3Onderzoek.getAanduidingGegevensInOnderzoekCode());
historie.setDatumTijdRegistratie(actie.getDatumTijdRegistratie());
historie.setDatumEinde(datumEinde);
historie.setActieInhoud(actie);
onderzoek.addOnderzoekHistorie(historie);
return onderzoek;
}
private BRPActie maakBrpActie() {
final AdministratieveHandeling administratieveHandeling = getAdministratieveHandeling();
final Timestamp datumtijdstempel =
FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonInschrijvingHistorieSet()).getDatumtijdstempel();
return new BRPActie(SoortActie.CONVERSIE_GBA, administratieveHandeling, administratieveHandeling.getPartij(), datumtijdstempel);
}
private AdministratieveHandeling getAdministratieveHandeling() {
return FormeleHistorieZonderVerantwoording.getActueelHistorieVoorkomen(persoon.getPersoonAfgeleidAdministratiefHistorieSet())
.getAdministratieveHandeling();
}
}
|
209258_0 | // http://www.youtube.com/watch?v=nR73DyBPAmg
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.EOFException;
import lejos.nxt.comm.USB;
import lejos.nxt.comm.USBConnection;
public class Main
{
public static void main(String [] args)
{
System.out.println("Hello Pinauto");
try
{
USBReceive();
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void USBReceive() throws IOException
{
// setup connection
USBConnection conn = USB.waitForConnection();
DataOutputStream dOut = conn.openDataOutputStream();
DataInputStream dIn = conn.openDataInputStream();
// motor speeds
Motors.SetSpeed(50, 20, 200);
while (true)
{
// receive
int i = dIn.readInt();
if (i > 0)
{
System.out.println("Received: "+i);
Motors.GetMoney(i);
}
// dummy break
else if (i == -1)
break;
}
// close connection
// wordt eigenlijk via pc afgesloten ipv hier
dOut.close();
dIn.close();
conn.close();
}
}
| Ketho/misc | edu/HRO/TIRPRJ01-3,4 Softwareontwikkeling/Lego NXT/NXT/Main.java | 356 | // wordt eigenlijk via pc afgesloten ipv hier | line_comment | nl | // http://www.youtube.com/watch?v=nR73DyBPAmg
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.EOFException;
import lejos.nxt.comm.USB;
import lejos.nxt.comm.USBConnection;
public class Main
{
public static void main(String [] args)
{
System.out.println("Hello Pinauto");
try
{
USBReceive();
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void USBReceive() throws IOException
{
// setup connection
USBConnection conn = USB.waitForConnection();
DataOutputStream dOut = conn.openDataOutputStream();
DataInputStream dIn = conn.openDataInputStream();
// motor speeds
Motors.SetSpeed(50, 20, 200);
while (true)
{
// receive
int i = dIn.readInt();
if (i > 0)
{
System.out.println("Received: "+i);
Motors.GetMoney(i);
}
// dummy break
else if (i == -1)
break;
}
// close connection
// wordt eigenlijk<SUF>
dOut.close();
dIn.close();
conn.close();
}
}
|
209269_1 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,478 | //hier kan je succes of failure halen uit de segmenstInURL | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan<SUF>
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} |
209269_7 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,478 | // eerst het resultaat van call verwerken om paymentid op te halen | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het<SUF>
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} |
209269_9 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,478 | // dit is de payment id | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is<SUF>
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} |
209269_11 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,478 | // 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden<SUF>
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} |
209284_2 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at [email protected]).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: [email protected]
******************************************************************************/
package com.lp.client.benutzer;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import com.lp.client.frame.component.InternalFrame;
import com.lp.client.pc.LPMain;
import com.lp.server.benutzer.service.SystemrolleDto;
@SuppressWarnings("static-access")
/*
* <p>&UUml;berschrift: </p> <p>Beschreibung: </p> <p>Copyright: Copyright (c)
* 2004</p> <p>Organisation: </p>
*
* @author Christian Kollmann
*
* @version $Revision: 1.4 $
*/
public class InternalFrameBenutzer extends InternalFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private TabbedPaneBenutzermandantsystemrolle tabbedPaneBenutzermandantsystemrolle = null;
private TabbedPaneBenutzer tabbedPaneBenutzer = null;
private TabbedPaneRollen tabbedPaneRollen = null;
private TabbedPaneNachrichten tabbedPaneNachrichten = null;
private final int IDX_TABBED_PANE_BENUTZER = 0;
private final int IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE = 1;
private final int IDX_TABBED_PANE_SYSTEMROLLE = 2;
private final int IDX_TABBED_PANE_NACHRICHTEN = 3;
private SystemrolleDto systemrolleDto = null;
public SystemrolleDto getSystemrolleDto() {
return systemrolleDto;
}
public void setSystemrolleDto(SystemrolleDto systemrolleDto) {
this.systemrolleDto = systemrolleDto;
}
public TabbedPaneBenutzermandantsystemrolle getTabbedPanePersonal() {
return tabbedPaneBenutzermandantsystemrolle;
}
public InternalFrameBenutzer(String title, String belegartCNr,
String sRechtModulweitI) throws Throwable {
super(title, belegartCNr, sRechtModulweitI);
jbInit();
initComponents();
}
private void jbInit() throws Throwable {
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"lp.benutzer"), null, null, LPMain.getInstance()
.getTextRespectUISPr("lp.benutzer"), IDX_TABBED_PANE_BENUTZER);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"benutzer.title.tab.benutzermandant"), null, null, LPMain
.getInstance().getTextRespectUISPr(
"benutzer.title.tab.benutzermandant"),
IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"lp.systemrolle"), null, null, LPMain.getInstance()
.getTextRespectUISPr("lp.systemrolle"),
IDX_TABBED_PANE_SYSTEMROLLE);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"ben.nachrichten"), null, null, LPMain.getInstance()
.getTextRespectUISPr("ben.nachrichten"),
IDX_TABBED_PANE_NACHRICHTEN);
registerChangeListeners();
createTabbedPaneBenutzer(null);
tabbedPaneBenutzer.lPEventObjectChanged(null);
tabbedPaneRoot.setSelectedComponent(tabbedPaneBenutzer);
// iicon: hier das li/on icon gemacht
ImageIcon iicon = new javax.swing.ImageIcon(getClass().getResource(
"/com/lp/client/res/user1_monitor16x16.png"));
setFrameIcon(iicon);
}
private void createTabbedPaneBenutzermandant(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneBenutzermandantsystemrolle = new TabbedPaneBenutzermandantsystemrolle(
this);
tabbedPaneRoot.setComponentAt(
IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE,
tabbedPaneBenutzermandantsystemrolle);
initComponents();
}
}
private void createTabbedPaneNachrichten(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneNachrichten = new TabbedPaneNachrichten(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_NACHRICHTEN,
tabbedPaneNachrichten);
initComponents();
}
}
private void createTabbedPaneRollen(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneRollen = new TabbedPaneRollen(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_SYSTEMROLLE,
tabbedPaneRollen);
initComponents();
}
}
private void createTabbedPaneBenutzer(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneBenutzer = new TabbedPaneBenutzer(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_BENUTZER,
tabbedPaneBenutzer);
initComponents();
}
}
public void lPStateChanged(EventObject e) throws Throwable {
JTabbedPane tabbedPane = (JTabbedPane) ((JTabbedPane) e.getSource())
.getSelectedComponent();
int selectedCur = ((JTabbedPane) e.getSource()).getSelectedIndex();
if (selectedCur == IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE) {
createTabbedPaneBenutzermandant(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneBenutzermandantsystemrolle.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_BENUTZER) {
createTabbedPaneBenutzer(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneBenutzer.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_SYSTEMROLLE) {
createTabbedPaneRollen(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneRollen.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_NACHRICHTEN) {
createTabbedPaneNachrichten(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneNachrichten.lPEventObjectChanged(null);
}
}
}
| heliumv/lpclientpc | src/com/lp/client/benutzer/InternalFrameBenutzer.java | 2,095 | // iicon: hier das li/on icon gemacht | line_comment | nl | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at [email protected]).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: [email protected]
******************************************************************************/
package com.lp.client.benutzer;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import com.lp.client.frame.component.InternalFrame;
import com.lp.client.pc.LPMain;
import com.lp.server.benutzer.service.SystemrolleDto;
@SuppressWarnings("static-access")
/*
* <p>&UUml;berschrift: </p> <p>Beschreibung: </p> <p>Copyright: Copyright (c)
* 2004</p> <p>Organisation: </p>
*
* @author Christian Kollmann
*
* @version $Revision: 1.4 $
*/
public class InternalFrameBenutzer extends InternalFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private TabbedPaneBenutzermandantsystemrolle tabbedPaneBenutzermandantsystemrolle = null;
private TabbedPaneBenutzer tabbedPaneBenutzer = null;
private TabbedPaneRollen tabbedPaneRollen = null;
private TabbedPaneNachrichten tabbedPaneNachrichten = null;
private final int IDX_TABBED_PANE_BENUTZER = 0;
private final int IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE = 1;
private final int IDX_TABBED_PANE_SYSTEMROLLE = 2;
private final int IDX_TABBED_PANE_NACHRICHTEN = 3;
private SystemrolleDto systemrolleDto = null;
public SystemrolleDto getSystemrolleDto() {
return systemrolleDto;
}
public void setSystemrolleDto(SystemrolleDto systemrolleDto) {
this.systemrolleDto = systemrolleDto;
}
public TabbedPaneBenutzermandantsystemrolle getTabbedPanePersonal() {
return tabbedPaneBenutzermandantsystemrolle;
}
public InternalFrameBenutzer(String title, String belegartCNr,
String sRechtModulweitI) throws Throwable {
super(title, belegartCNr, sRechtModulweitI);
jbInit();
initComponents();
}
private void jbInit() throws Throwable {
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"lp.benutzer"), null, null, LPMain.getInstance()
.getTextRespectUISPr("lp.benutzer"), IDX_TABBED_PANE_BENUTZER);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"benutzer.title.tab.benutzermandant"), null, null, LPMain
.getInstance().getTextRespectUISPr(
"benutzer.title.tab.benutzermandant"),
IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"lp.systemrolle"), null, null, LPMain.getInstance()
.getTextRespectUISPr("lp.systemrolle"),
IDX_TABBED_PANE_SYSTEMROLLE);
tabbedPaneRoot.insertTab(LPMain.getInstance().getTextRespectUISPr(
"ben.nachrichten"), null, null, LPMain.getInstance()
.getTextRespectUISPr("ben.nachrichten"),
IDX_TABBED_PANE_NACHRICHTEN);
registerChangeListeners();
createTabbedPaneBenutzer(null);
tabbedPaneBenutzer.lPEventObjectChanged(null);
tabbedPaneRoot.setSelectedComponent(tabbedPaneBenutzer);
// iicon: hier<SUF>
ImageIcon iicon = new javax.swing.ImageIcon(getClass().getResource(
"/com/lp/client/res/user1_monitor16x16.png"));
setFrameIcon(iicon);
}
private void createTabbedPaneBenutzermandant(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneBenutzermandantsystemrolle = new TabbedPaneBenutzermandantsystemrolle(
this);
tabbedPaneRoot.setComponentAt(
IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE,
tabbedPaneBenutzermandantsystemrolle);
initComponents();
}
}
private void createTabbedPaneNachrichten(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneNachrichten = new TabbedPaneNachrichten(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_NACHRICHTEN,
tabbedPaneNachrichten);
initComponents();
}
}
private void createTabbedPaneRollen(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneRollen = new TabbedPaneRollen(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_SYSTEMROLLE,
tabbedPaneRollen);
initComponents();
}
}
private void createTabbedPaneBenutzer(JTabbedPane tabbedPane)
throws Throwable {
if (tabbedPane == null) {
// lazy loading
tabbedPaneBenutzer = new TabbedPaneBenutzer(this);
tabbedPaneRoot.setComponentAt(IDX_TABBED_PANE_BENUTZER,
tabbedPaneBenutzer);
initComponents();
}
}
public void lPStateChanged(EventObject e) throws Throwable {
JTabbedPane tabbedPane = (JTabbedPane) ((JTabbedPane) e.getSource())
.getSelectedComponent();
int selectedCur = ((JTabbedPane) e.getSource()).getSelectedIndex();
if (selectedCur == IDX_TABBED_PANE_BENUTZERMANDANTSYSTEMROLLE) {
createTabbedPaneBenutzermandant(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneBenutzermandantsystemrolle.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_BENUTZER) {
createTabbedPaneBenutzer(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneBenutzer.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_SYSTEMROLLE) {
createTabbedPaneRollen(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneRollen.lPEventObjectChanged(null);
} else if (selectedCur == IDX_TABBED_PANE_NACHRICHTEN) {
createTabbedPaneNachrichten(tabbedPane);
// Info an Tabbedpane, bist selektiert worden.
tabbedPaneNachrichten.lPEventObjectChanged(null);
}
}
}
|
209297_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.parts;
import java.rmi.RemoteException;
import org.eclipse.swt.widgets.TableItem;
import de.willuhn.datasource.GenericIterator;
import de.willuhn.datasource.rmi.DBIterator;
import de.willuhn.jameica.gui.Action;
import de.willuhn.jameica.gui.Part;
import de.willuhn.jameica.gui.formatter.DateFormatter;
import de.willuhn.jameica.gui.formatter.Formatter;
import de.willuhn.jameica.gui.formatter.TableFormatter;
import de.willuhn.jameica.gui.parts.TablePart;
import de.willuhn.jameica.gui.util.Font;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.hbci.HBCIProperties;
import de.willuhn.jameica.hbci.Settings;
import de.willuhn.jameica.hbci.rmi.HBCIDBService;
import de.willuhn.jameica.hbci.rmi.Nachricht;
import de.willuhn.jameica.system.Application;
import de.willuhn.logging.Logger;
import de.willuhn.util.I18N;
/**
* Implementierung einer fix und fertig vorkonfigurierten Liste mit System-Nachrichten.
*/
public class NachrichtList extends TablePart implements Part
{
private I18N i18n = null;
/**
* ct.
* @param action
* @throws RemoteException
*/
public NachrichtList(Action action) throws RemoteException
{
this(init(), action);
}
/**
* ct.
* @param list Liste der Nachrichten.
* @param action
*/
public NachrichtList(GenericIterator list, Action action)
{
super(list,action);
this.setMulti(true);
this.i18n = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N();
setFormatter(new TableFormatter()
{
public void format(TableItem item)
{
if (item == null || item.getData() == null)
return;
Nachricht n = (Nachricht) item.getData();
try
{
item.setFont(n.isGelesen() ? Font.DEFAULT.getSWTFont() : Font.BOLD.getSWTFont());
}
catch (RemoteException e)
{
Logger.error("error while checking for message read status",e);
}
}
});
addColumn(i18n.tr("Datum"),"datum",new DateFormatter(HBCI.DATEFORMAT));
addColumn(i18n.tr("Bank"),"blz", new Formatter()
{
public String format(Object o)
{
if (o == null)
return null;
String blz = o.toString();
return i18n.tr("{0} [BLZ: {1}]", HBCIProperties.getNameForBank(blz), blz);
}
});
addColumn(i18n.tr("Nachricht"),"nachricht", new Formatter() {
public String format(Object o)
{
if (o == null)
return null;
String s = (String) o;
if (s.indexOf('\n') != -1)
return s;
// Ist das eine Sparkassen-Eigenart, dass die Nachrichten Festbreite haben?
// Na gut, dann nehmen wir die alle ueberfluessigen Leerzeichen raus und brechen hart um.
s = s.replaceAll("( {1,})"," ");
s = s.replaceAll("(.{77})","$1\n");
return s;
}
});
setContextMenu(new de.willuhn.jameica.hbci.gui.menus.NachrichtList());
}
/**
* Liefert die sortierte Nachrichtenliste.
* Das ist nur deshalb in einer extra Funktion ausgegliedert, weil der
* Aufruf des super-Konstruktors zwingend in der ersten Zeile erfolgen muss.
* @return Liste.
* @throws RemoteException
*/
private static DBIterator init() throws RemoteException
{
HBCIDBService service = (HBCIDBService) Settings.getDBService();
DBIterator list = service.createList(Nachricht.class);
list.setOrder("ORDER BY gelesen, blz, " + service.getSQLTimestamp("datum") + " desc");
return list;
}
}
/**********************************************************************
* $Log: NachrichtList.java,v $
* Revision 1.7 2011/06/30 16:29:41 willuhn
* @N Unterstuetzung fuer neues UnreadCount-Feature
*
* Revision 1.6 2008/12/17 22:53:39 willuhn
* @R t o d o tag entfernt
*
* Revision 1.5 2007/04/19 18:12:21 willuhn
* @N MySQL-Support (GUI zum Konfigurieren fehlt noch)
*
* Revision 1.4 2006/11/16 22:29:46 willuhn
* @N Bug 331
*
* Revision 1.3 2006/03/23 23:44:58 willuhn
* @N Umbruch der System-Nachrichten
*
* Revision 1.2 2005/11/09 01:13:53 willuhn
* @N chipcard modul fuer AMD64 vergessen
* @N Startseite jetzt frei konfigurierbar
*
* Revision 1.1 2005/05/09 17:26:56 web0
* @N Bugzilla 68
*
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/gui/parts/NachrichtList.java | 1,514 | /**
* ct.
* @param list Liste der Nachrichten.
* @param action
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.parts;
import java.rmi.RemoteException;
import org.eclipse.swt.widgets.TableItem;
import de.willuhn.datasource.GenericIterator;
import de.willuhn.datasource.rmi.DBIterator;
import de.willuhn.jameica.gui.Action;
import de.willuhn.jameica.gui.Part;
import de.willuhn.jameica.gui.formatter.DateFormatter;
import de.willuhn.jameica.gui.formatter.Formatter;
import de.willuhn.jameica.gui.formatter.TableFormatter;
import de.willuhn.jameica.gui.parts.TablePart;
import de.willuhn.jameica.gui.util.Font;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.hbci.HBCIProperties;
import de.willuhn.jameica.hbci.Settings;
import de.willuhn.jameica.hbci.rmi.HBCIDBService;
import de.willuhn.jameica.hbci.rmi.Nachricht;
import de.willuhn.jameica.system.Application;
import de.willuhn.logging.Logger;
import de.willuhn.util.I18N;
/**
* Implementierung einer fix und fertig vorkonfigurierten Liste mit System-Nachrichten.
*/
public class NachrichtList extends TablePart implements Part
{
private I18N i18n = null;
/**
* ct.
* @param action
* @throws RemoteException
*/
public NachrichtList(Action action) throws RemoteException
{
this(init(), action);
}
/**
* ct.
<SUF>*/
public NachrichtList(GenericIterator list, Action action)
{
super(list,action);
this.setMulti(true);
this.i18n = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N();
setFormatter(new TableFormatter()
{
public void format(TableItem item)
{
if (item == null || item.getData() == null)
return;
Nachricht n = (Nachricht) item.getData();
try
{
item.setFont(n.isGelesen() ? Font.DEFAULT.getSWTFont() : Font.BOLD.getSWTFont());
}
catch (RemoteException e)
{
Logger.error("error while checking for message read status",e);
}
}
});
addColumn(i18n.tr("Datum"),"datum",new DateFormatter(HBCI.DATEFORMAT));
addColumn(i18n.tr("Bank"),"blz", new Formatter()
{
public String format(Object o)
{
if (o == null)
return null;
String blz = o.toString();
return i18n.tr("{0} [BLZ: {1}]", HBCIProperties.getNameForBank(blz), blz);
}
});
addColumn(i18n.tr("Nachricht"),"nachricht", new Formatter() {
public String format(Object o)
{
if (o == null)
return null;
String s = (String) o;
if (s.indexOf('\n') != -1)
return s;
// Ist das eine Sparkassen-Eigenart, dass die Nachrichten Festbreite haben?
// Na gut, dann nehmen wir die alle ueberfluessigen Leerzeichen raus und brechen hart um.
s = s.replaceAll("( {1,})"," ");
s = s.replaceAll("(.{77})","$1\n");
return s;
}
});
setContextMenu(new de.willuhn.jameica.hbci.gui.menus.NachrichtList());
}
/**
* Liefert die sortierte Nachrichtenliste.
* Das ist nur deshalb in einer extra Funktion ausgegliedert, weil der
* Aufruf des super-Konstruktors zwingend in der ersten Zeile erfolgen muss.
* @return Liste.
* @throws RemoteException
*/
private static DBIterator init() throws RemoteException
{
HBCIDBService service = (HBCIDBService) Settings.getDBService();
DBIterator list = service.createList(Nachricht.class);
list.setOrder("ORDER BY gelesen, blz, " + service.getSQLTimestamp("datum") + " desc");
return list;
}
}
/**********************************************************************
* $Log: NachrichtList.java,v $
* Revision 1.7 2011/06/30 16:29:41 willuhn
* @N Unterstuetzung fuer neues UnreadCount-Feature
*
* Revision 1.6 2008/12/17 22:53:39 willuhn
* @R t o d o tag entfernt
*
* Revision 1.5 2007/04/19 18:12:21 willuhn
* @N MySQL-Support (GUI zum Konfigurieren fehlt noch)
*
* Revision 1.4 2006/11/16 22:29:46 willuhn
* @N Bug 331
*
* Revision 1.3 2006/03/23 23:44:58 willuhn
* @N Umbruch der System-Nachrichten
*
* Revision 1.2 2005/11/09 01:13:53 willuhn
* @N chipcard modul fuer AMD64 vergessen
* @N Startseite jetzt frei konfigurierbar
*
* Revision 1.1 2005/05/09 17:26:56 web0
* @N Bugzilla 68
*
**********************************************************************/ |
209300_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.action;
import de.willuhn.jameica.gui.Action;
import de.willuhn.jameica.gui.GUI;
import de.willuhn.jameica.hbci.rmi.Nachricht;
import de.willuhn.util.ApplicationException;
/**
* Action zum Oeffnen einer System-Nachricht.
*/
public class NachrichtOpen implements Action
{
/**
* Als Context kann ein Objekt vom Typ Nachricht uebergeben werden.
* @see de.willuhn.jameica.gui.Action#handleAction(java.lang.Object)
*/
public void handleAction(Object context) throws ApplicationException
{
if (!(context instanceof Nachricht))
return;
GUI.startView(de.willuhn.jameica.hbci.gui.views.NachrichtDetails.class,context);
}
}
/**********************************************************************
* $Log: NachrichtOpen.java,v $
* Revision 1.1 2009/07/17 08:42:57 willuhn
* @N Detail-Ansicht fuer Systemnachrichten der Bank
* @N Systemnachrichten in Zwischenablage kopieren
*
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/gui/action/NachrichtOpen.java | 370 | /**
* Als Context kann ein Objekt vom Typ Nachricht uebergeben werden.
* @see de.willuhn.jameica.gui.Action#handleAction(java.lang.Object)
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.action;
import de.willuhn.jameica.gui.Action;
import de.willuhn.jameica.gui.GUI;
import de.willuhn.jameica.hbci.rmi.Nachricht;
import de.willuhn.util.ApplicationException;
/**
* Action zum Oeffnen einer System-Nachricht.
*/
public class NachrichtOpen implements Action
{
/**
* Als Context kann<SUF>*/
public void handleAction(Object context) throws ApplicationException
{
if (!(context instanceof Nachricht))
return;
GUI.startView(de.willuhn.jameica.hbci.gui.views.NachrichtDetails.class,context);
}
}
/**********************************************************************
* $Log: NachrichtOpen.java,v $
* Revision 1.1 2009/07/17 08:42:57 willuhn
* @N Detail-Ansicht fuer Systemnachrichten der Bank
* @N Systemnachrichten in Zwischenablage kopieren
*
**********************************************************************/ |
209318_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.system.Application;
/**
* Implementierung fuer die Default-Einstellungen eines
* selbstkonfigurierten Readers.
*/
public class CustomReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N().tr("Benutzerdefinierter CTAPI-Leser");
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
}
/**********************************************************************
* $Log: CustomReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/CustomReader.java | 578 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.system.Application;
/**
* Implementierung fuer die Default-Einstellungen eines
* selbstkonfigurierten Readers.
*/
public class CustomReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
<SUF>*/
public String getName()
{
return Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N().tr("Benutzerdefinierter CTAPI-Leser");
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
}
/**********************************************************************
* $Log: CustomReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209318_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.system.Application;
/**
* Implementierung fuer die Default-Einstellungen eines
* selbstkonfigurierten Readers.
*/
public class CustomReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N().tr("Benutzerdefinierter CTAPI-Leser");
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
}
/**********************************************************************
* $Log: CustomReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/CustomReader.java | 578 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.system.Application;
/**
* Implementierung fuer die Default-Einstellungen eines
* selbstkonfigurierten Readers.
*/
public class CustomReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N().tr("Benutzerdefinierter CTAPI-Leser");
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
}
/**********************************************************************
* $Log: CustomReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209327_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
/**
* Implementierung fuer die Default-Einstellungen des
* Kartenlesers Kaan TriB@nk.
*/
public class KaanTriBankReader extends AbstractKaanReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Kaan TriB@nk";
}
}
/**********************************************************************
* $Log: KaanTriBankReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/KaanTriBankReader.java | 367 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
/**
* Implementierung fuer die Default-Einstellungen des
* Kartenlesers Kaan TriB@nk.
*/
public class KaanTriBankReader extends AbstractKaanReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
<SUF>*/
public String getName()
{
return "CTAPI: Kaan TriB@nk";
}
}
/**********************************************************************
* $Log: KaanTriBankReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209331_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen der
* Kartenleser-Reihe Cherry Smartboard.
*/
public class CherrySmartboardReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Cherry Smartboard";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CTChyCTApiSp.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: CherrySmartboardReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/CherrySmartboardReader.java | 579 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen der
* Kartenleser-Reihe Cherry Smartboard.
*/
public class CherrySmartboardReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
<SUF>*/
public String getName()
{
return "CTAPI: Cherry Smartboard";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CTChyCTApiSp.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: CherrySmartboardReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209331_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen der
* Kartenleser-Reihe Cherry Smartboard.
*/
public class CherrySmartboardReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Cherry Smartboard";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CTChyCTApiSp.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: CherrySmartboardReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/CherrySmartboardReader.java | 579 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen der
* Kartenleser-Reihe Cherry Smartboard.
*/
public class CherrySmartboardReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Cherry Smartboard";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CTChyCTApiSp.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: CherrySmartboardReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209337_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "Chipdrive PinPad 532" von Towitoko/SCM/Chipdrive.
*/
public class ChipDrivePinPad532Reader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Chipdrive Pinpad / SCM SPR 332";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
if (Application.getPlatform().getOS() == Platform.OS_WINDOWS)
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctpcsc32.dll";
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: ChipDrivePinPad532Reader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/ChipDrivePinPad532Reader.java | 591 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "Chipdrive PinPad 532" von Towitoko/SCM/Chipdrive.
*/
public class ChipDrivePinPad532Reader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Chipdrive Pinpad / SCM SPR 332";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
if (Application.getPlatform().getOS() == Platform.OS_WINDOWS)
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctpcsc32.dll";
return "";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
return Application.getPlatform().getOS() == Platform.OS_WINDOWS;
}
}
/**********************************************************************
* $Log: ChipDrivePinPad532Reader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209344_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Basis-Implementierung fuer die Default-Einstellungen von Kaan-Readern.
*/
public abstract class AbstractKaanReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
// Wir schauen mal, ob der CT-Treiber im System installiert ist
File f32 = new File("/usr/lib/libct.so");
if (f32.exists())
return f32.getAbsolutePath();
// Ne, dann nehmen wir den mitgelieferten
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libct.so";
case Platform.OS_LINUX_64:
// Wir schauen mal, ob der CT-Treiber im System installiert ist
File f64 = new File("/usr/lib64/libct.so");
if (f64.exists())
return f64.getAbsolutePath();
return "";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CT32.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_LINUX_64;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return false;
}
}
/**********************************************************************
* $Log: AbstractKaanReader.java,v $
* Revision 1.2 2010/09/07 15:28:04 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/AbstractKaanReader.java | 779 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Basis-Implementierung fuer die Default-Einstellungen von Kaan-Readern.
*/
public abstract class AbstractKaanReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
// Wir schauen mal, ob der CT-Treiber im System installiert ist
File f32 = new File("/usr/lib/libct.so");
if (f32.exists())
return f32.getAbsolutePath();
// Ne, dann nehmen wir den mitgelieferten
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libct.so";
case Platform.OS_LINUX_64:
// Wir schauen mal, ob der CT-Treiber im System installiert ist
File f64 = new File("/usr/lib64/libct.so");
if (f64.exists())
return f64.getAbsolutePath();
return "";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "CT32.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_LINUX_64;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return false;
}
}
/**********************************************************************
* $Log: AbstractKaanReader.java,v $
* Revision 1.2 2010/09/07 15:28:04 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209349_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "Chipdrive Micro" von Towitoko/SCM/Chipdrive.
*/
public class ChipDriveMicroReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Chipdrive Micro / Towitoko Kartenzwerg";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libtowitoko-2.0.7.so";
case Platform.OS_LINUX_64:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libtowitoko-2.0.7-amd64.so";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "cttwkw32.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_LINUX_64;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.server.AbstractReader#getPort()
*/
public String getPort()
{
return "COM/USB";
}
}
/**********************************************************************
* $Log: ChipDriveMicroReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/ChipDriveMicroReader.java | 825 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "Chipdrive Micro" von Towitoko/SCM/Chipdrive.
*/
public class ChipDriveMicroReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: Chipdrive Micro / Towitoko Kartenzwerg";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libtowitoko-2.0.7.so";
case Platform.OS_LINUX_64:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "libtowitoko-2.0.7-amd64.so";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "cttwkw32.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_LINUX_64;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#useSoftPin()
*/
public boolean useSoftPin()
{
return true;
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.server.AbstractReader#getPort()
*/
public String getPort()
{
return "COM/USB";
}
}
/**********************************************************************
* $Log: ChipDriveMicroReader.java,v $
* Revision 1.2 2010/09/07 15:28:05 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.1 2010/06/17 11:45:49 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209354_3 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "CyberJack PinPad" von ReinerSCT.
*/
public class ReinerSCTCyberJackReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: ReinerSCT cyberjack";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
return "/usr/lib/libctapi-cyberjack.so";
case Platform.OS_LINUX_64:
return "/usr/lib64/libctapi-cyberjack.so";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctrsct32.dll";
case Platform.OS_WINDOWS_64:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctrsct64.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_WINDOWS_64 ||
os == Platform.OS_LINUX_64;
}
}
/**********************************************************************
* $Log: ReinerSCTCyberJackReader.java,v $
* Revision 1.4 2012/05/18 13:08:57 willuhn
* @B BUGZILLA 1236
*
* Revision 1.3 2010-09-07 15:28:04 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.2 2010-07-25 23:56:09 willuhn
* @N Suchpfad fuer Windows 64Bit-CTAPI-Treiber (siehe Mail von Tobias vom 26.07.2010)
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ | willuhn/hibiscus | src/de/willuhn/jameica/hbci/passports/ddv/server/ReinerSCTCyberJackReader.java | 834 | /**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.hbci.passports.ddv.server;
import java.io.File;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Platform;
/**
* Implementierung fuer die Default-Einstellungen des
* "CyberJack PinPad" von ReinerSCT.
*/
public class ReinerSCTCyberJackReader extends AbstractReader
{
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getName()
*/
public String getName()
{
return "CTAPI: ReinerSCT cyberjack";
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#getCTAPIDriver()
<SUF>*/
public String getCTAPIDriver()
{
switch (Application.getPlatform().getOS())
{
case Platform.OS_LINUX:
return "/usr/lib/libctapi-cyberjack.so";
case Platform.OS_LINUX_64:
return "/usr/lib64/libctapi-cyberjack.so";
case Platform.OS_WINDOWS:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctrsct32.dll";
case Platform.OS_WINDOWS_64:
return getCTAPIDriverPath().getAbsolutePath() + File.separator + "ctrsct64.dll";
default:
return "";
}
}
/**
* @see de.willuhn.jameica.hbci.passports.ddv.rmi.Reader#isSupported()
*/
public boolean isSupported()
{
int os = Application.getPlatform().getOS();
return os == Platform.OS_LINUX ||
os == Platform.OS_WINDOWS ||
os == Platform.OS_WINDOWS_64 ||
os == Platform.OS_LINUX_64;
}
}
/**********************************************************************
* $Log: ReinerSCTCyberJackReader.java,v $
* Revision 1.4 2012/05/18 13:08:57 willuhn
* @B BUGZILLA 1236
*
* Revision 1.3 2010-09-07 15:28:04 willuhn
* @N BUGZILLA 391 - Kartenleser-Konfiguration komplett umgebaut. Damit lassen sich jetzt beliebig viele Kartenleser und Konfigurationen parellel einrichten
*
* Revision 1.2 2010-07-25 23:56:09 willuhn
* @N Suchpfad fuer Windows 64Bit-CTAPI-Treiber (siehe Mail von Tobias vom 26.07.2010)
*
* Revision 1.1 2010/06/17 11:45:48 willuhn
* @C kompletten Code aus "hbci_passport_ddv" in Hibiscus verschoben - es macht eigentlich keinen Sinn mehr, das in separaten Projekten zu fuehren
**********************************************************************/ |
209386_0 | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| zowievangeest/IMTPMD | app/src/main/java/imtpmd/imtpmd_stoplicht/API/API.java | 1,801 | //188.226.134.236/api/meeting/" + meeting_id); | line_comment | nl | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" +<SUF>
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
209386_1 | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| zowievangeest/IMTPMD | app/src/main/java/imtpmd/imtpmd_stoplicht/API/API.java | 1,801 | //188.226.134.236/api/meeting/" + meeting_id); | line_comment | nl | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" +<SUF>
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
209386_3 | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| zowievangeest/IMTPMD | app/src/main/java/imtpmd/imtpmd_stoplicht/API/API.java | 1,801 | //188.226.134.236/api/meeting/" + meeting_id); | line_comment | nl | package imtpmd.imtpmd_stoplicht.API;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import imtpmd.imtpmd_stoplicht.Models.Date;
import imtpmd.imtpmd_stoplicht.Models.Emotion;
import imtpmd.imtpmd_stoplicht.Models.Feedback;
import imtpmd.imtpmd_stoplicht.Models.FeedbackStats;
import imtpmd.imtpmd_stoplicht.Models.Meeting;
import imtpmd.imtpmd_stoplicht.Models.User;
public class API {
public static void login (String login_number_new) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", login_number_new));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static ArrayList<Meeting> getAllMeetings() {
ArrayList<Meeting> meetings = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject meeting = jsonArray.getJSONObject(i);
JSONObject user = meeting.getJSONObject("user");
meetings.add(new Meeting(
meeting.getInt("id"),
new User(
user.getInt("id"),
user.getString("number")
),
meeting.getString("name"),
meeting.getString("description"),
new Date(meeting.getString("starting_at")),
new Date(meeting.getString("ending_at"))
));
}
} catch (Exception e) {}
return meetings;
}
public static Meeting getMeetingById(int meeting_id) {
Meeting meeting = new Meeting();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
meeting.setName(jsonObject.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}
return meeting;
}
public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) {
ArrayList<Feedback> feedback = new ArrayList<>();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONArray jsonArray = jsonObject.getJSONArray("feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject the_feedback = jsonArray.getJSONObject(i);
JSONObject emotion = the_feedback.getJSONObject("emotion");
JSONObject user = the_feedback.getJSONObject("user");
// Fill what we need.
feedback.add(
new Feedback(
the_feedback.getInt("id"),
new Emotion(emotion.getString("name"), emotion.getString("slug")),
new User(user.getString("number")),
the_feedback.getString("description"),
new Date(the_feedback.getString("created_at"))
)
);
}
} catch (Exception e) {
e.printStackTrace();
}
return feedback;
}
public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) {
FeedbackStats feedbackStats = new FeedbackStats();
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" +<SUF>
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
JSONObject jsonObject = new JSONObject(reader.readLine());
JSONObject stats = jsonObject.getJSONObject("feedback_stats");
feedbackStats.setBlij(stats.getInt("blij"));
feedbackStats.setNeutraal(stats.getInt("neutraal"));
feedbackStats.setVerdrietig(stats.getInt("verdrietig"));
} catch (Exception e) {
e.printStackTrace();
}
return feedbackStats;
}
public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id)));
pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id)));
pairs.add(new BasicNameValuePair("number", username));
pairs.add(new BasicNameValuePair("description", description));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {}
}
public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) {
Log.d("starting", starting_at);
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting");
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("number", number));
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("description", description));
pairs.add(new BasicNameValuePair("starting_at", starting_at));
pairs.add(new BasicNameValuePair("ending_at", ending_at));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
defaultHttpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
209412_20 | package com.crash.boozl.boozl.code;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.crash.boozl.boozl.code.Alcohols.Beer;
import com.crash.boozl.boozl.code.Alcohols.Gin;
import com.crash.boozl.boozl.code.Alcohols.Rum;
import com.crash.boozl.boozl.code.Alcohols.Tequila;
import com.crash.boozl.boozl.code.Alcohols.Vodka;
import com.crash.boozl.boozl.code.Alcohols.Whisky;
import com.crash.boozl.boozl.code.Alcohols.Wine;
import com.google.android.gms.maps.model.LatLng;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Search extends FragmentActivity {
private DrawerLayout mDrawerLayout;
RelativeLayout mDockLayout;
ImageView search_menu, searchCancel;
ListView lv_Results;
ImageButton menu;
// Gridview variables
GridView gv_alcoholType;
RadioGroup rg_display, rg_sort;
Switch switch_list_map;
Search search;
TextView activity_description;
Button btn_network_status, btn_location_status;
Location userLocation = null;
LocationHandler myLocation;
public boolean is_Connected_To_Internet = false;
boolean mIsReceiverRegistered_Internet = false;
InternetBroadcastReceiver mReceiver_Internet = null;
InternetHandler internet;
boolean mIsReceiverRegistered = false;
LocationBroadcastReceiver mReceiver = null;
final ArrayList<Deal> al_testDeals = new ArrayList<Deal>();
public static FragmentManager fragment_manager;
Map map;
String LOG_TAG = Search.class.getSimpleName();
Fragment_Deal_Info fragment_deal_info;
Fragment_Store_Info fragment_store_info;
AutoCompleteTextView autocompletetv_Search;
// Used to populate each different gridview on the DrawerLayout
ArrayList<Item> gridItems_alcoholType = new ArrayList<Item>();
ArrayList<Store> al_Stores = new ArrayList<Store>();
ArrayList<ParseObject> storeHolder = new ArrayList<ParseObject>();
CustomListViewAdapter adapter;
// Creates a custom GridView adapter that is applied to each adapter
CustomGridViewAdapter customGridViewAdapter_Alcohol;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
System.out.println("No saved instance");
fragment_deal_info = new Fragment_Deal_Info();
fragment_deal_info.setActivity_search(this);
fragment_store_info = new Fragment_Store_Info();
fragment_store_info.setActivity_search(this);
}
else {
if((Fragment_Deal_Info) getFragmentManager().findFragmentByTag("Deal_Info") != null) {
fragment_deal_info = (Fragment_Deal_Info) getFragmentManager().findFragmentByTag("Deal_Info");
fragment_store_info = (Fragment_Store_Info) getFragmentManager().findFragmentByTag("Store_Info");
}
else{
fragment_deal_info = new Fragment_Deal_Info();
fragment_deal_info.setActivity_search(this);
fragment_store_info = new Fragment_Store_Info();
fragment_store_info.setActivity_search(this);
}
}
// Enable Local Datastore.
// Sometimes get an error here! Not sure why... It happens after going to the Galaxy Main Screen then re opening the app
Parse.enableLocalDatastore(this);
Parse.initialize(this, "ibsGWbLLA1BsbYWCd163g2vVJMd9LrhE6vmIovj2", "Vy8jgDckbEu3D5258KJSmSftShHqGHukeMtWliHs");
setContentView(R.layout.activity_search);
search_menu = (ImageView) findViewById(R.id.menu_imageView);
searchCancel = (ImageView) findViewById((R.id.imgbtn_search_cancel));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDockLayout = (RelativeLayout) findViewById(R.id.dockedLayout);
lv_Results = (ListView) findViewById(R.id.lv_results);
gv_alcoholType = (GridView) findViewById(R.id.gridview_alcohol_selection);
// rg_display = (RadioGroup) findViewById(R.id.rg_display);
rg_sort = (RadioGroup) findViewById(R.id.rg_sort);
switch_list_map = (Switch) findViewById(R.id.switch_toggle);
autocompletetv_Search = (AutoCompleteTextView) findViewById(R.id.autocompletetv_search);
activity_description = (TextView) findViewById(R.id.zone_name);
btn_network_status = (Button) findViewById(R.id.btn_network_alert);
btn_location_status = (Button) findViewById(R.id.btn_location_alert);
// menu = (ImageButton) findViewById(R.id.imgbtn_menu);
search = this;
map = new Map();
map.setSearch(this);
fragment_manager = getFragmentManager();
map = new Map();
adapter = new CustomListViewAdapter(search, al_testDeals);
lv_Results.setAdapter(adapter);
internet = new InternetHandler(this, this);
is_Connected_To_Internet = internet.networkCheck();
if(is_Connected_To_Internet){
// getStores();
}
else{
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
}
// Get the deals from Parse database and populate the deal listview
// getDeals();
LocationHandler.LocationResult locationResult = new LocationHandler.LocationResult(){
@Override
public void gotLocation(Location location) {
//Got the location!
// Location was not found... Should display something to the user or try again
Log.d(LOG_TAG, "Search is Finding the Location!");
if (location == null) {
Log.d(LOG_TAG, "Location not found");
userLocation = location;
} else {
Log.d(LOG_TAG, "Location found!");
userLocation = location;
System.out.println("Is userLocation null: " + userLocation == null);
Search.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
update_Location_Alert(userLocation);
}
});
userLocation = location;
}
}
};
//
//
update_Location_Alert(userLocation);
myLocation = new LocationHandler(this, this);
myLocation.getLocation(this, locationResult);
// Create the grid view icons
// Alcohol Type Icons
Bitmap beerIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.beer_icon);
Bitmap wineIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.wine_icon);
Bitmap vodkaIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.vodka_icon);
Bitmap whiskyIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.whisky_icon);
Bitmap tequilaIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.tequila_icon);
Bitmap ginIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
final Bitmap rumIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
Bitmap kegIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
Bitmap storeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
// Sort by Icons
Bitmap a_to_zIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.a_to_z_icon);
Bitmap sizeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.size_icon);
Bitmap priceIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.price_icon);
Bitmap distanceIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.distance_icon);
// Add the icons and text to the different grid views
// Alcohol Type
gridItems_alcoholType.add(new Item(beerIcon, "Beer"));
gridItems_alcoholType.add(new Item(wineIcon, "Wine"));
gridItems_alcoholType.add(new Item(vodkaIcon, "Vodka"));
gridItems_alcoholType.add(new Item(whiskyIcon, "Whisky"));
gridItems_alcoholType.add(new Item(tequilaIcon, "Tequila"));
gridItems_alcoholType.add(new Item(ginIcon, "Gin"));
gridItems_alcoholType.add(new Item(rumIcon, "Rum"));
gridItems_alcoholType.add(new Item(kegIcon, "Keg"));
gridItems_alcoholType.add(new Item(storeIcon, "Store"));
search_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(mDockLayout);
}
});
// searchCancel is used to remove all the text the user has used to search.... Prevents the user from having to backspace
//Throughout the entire text in order to clear the search
searchCancel.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
autocompletetv_Search.setText("");
}
});
btn_network_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(Search.this);
dialog.setMessage(Search.this.getResources().getString(R.string.network_not_enabled));
dialog.setPositiveButton(Search.this.getResources().getString(R.string.open_network_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// Wong INTENT!
Intent myIntent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
Search.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(Search.this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
});
btn_location_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
customGridViewAdapter_Alcohol = new CustomGridViewAdapter(this, R.layout.row_grid, gridItems_alcoholType, this);
gv_alcoholType.setAdapter(customGridViewAdapter_Alcohol);
for(int i = 0; i < gridItems_alcoholType.size(); i++){
gridItems_alcoholType.get(i).toggleCheck();
}
switch_list_map.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked){
if(fragment_deal_info.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_deal_info);
transaction.commit();
}
else if(fragment_store_info.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_store_info);
transaction.commit();
}
else if(map.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(map);
transaction.commit();
}
activity_description.setText("Results");
}
else{
if (fragment_deal_info.isAdded()) {
System.out.println("Deal info is currently visible!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
} else if (fragment_store_info.isAdded()) {
System.out.println("Store info is currently visible!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
} else if (!map.isAdded()) {
System.out.println("Map has not been added yet!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
}
activity_description.setText("Results");
}
}
});
rg_sort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rb_a_to_z) {
adapter.sortDeals(R.id.rb_a_to_z);
} else if (checkedId == R.id.rb_price) {
adapter.sortDeals(R.id.rb_price);
} else if (checkedId == R.id.rb_size) {
adapter.sortDeals(R.id.rb_size);
} else if (checkedId == R.id.rb_distance) {
adapter.sortDeals(R.id.rb_distance);
}
}
});
// Adds a text watcher to the AutoComplete Search bar so that the results can be filtered out
autocompletetv_Search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = autocompletetv_Search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
adapter.sortDeals(rg_sort.getCheckedRadioButtonId());
// Update the map
if (search.map.isResumed()) {
map.showDeals();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
autocompletetv_Search.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
mDrawerLayout.closeDrawer(mDockLayout);
// Clicking the autocomplete search accessory button will take you to the Map view with the deals if the Mapview radio button is currently checked
if(fragment_store_info.isAdded() || fragment_deal_info.isAdded() && switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
map.setSearch(search);
transaction.commit();
}
// Otherwise it will take you to the Search activity with the List view displaying all the deals
else if(fragment_deal_info.isAdded() && !switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_deal_info);
transaction.commit();
}
else if(fragment_store_info.isAdded() && !switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_store_info);
transaction.commit();
}
handled = true;
}
return handled;
}
});
}
@Override
protected void onDestroy() {
System.out.println("Destroying Search");
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_settings, popup.getMenu());
popup.show();
}
@Override
public void onBackPressed() {
if(fragment_manager.getBackStackEntryCount() != 0) {
fragment_manager.popBackStack();
} else {
activity_description.setText("Results");
super.onBackPressed();
}
}
public void getDeals() {
System.out.println("getDeals called!");
System.out.println("Size of stores is: " + al_Stores.size());
for (int z = 0; z < al_Stores.size(); z++) {
final int j = z;
ParseQuery<ParseObject> query = ParseQuery.getQuery("Alcohol").whereEqualTo("Store", storeHolder.get(z));
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> alcohol, ParseException e) {
if (e == null) {
ArrayList<ParseObject> tempIDHolder = new ArrayList<ParseObject>();
// your logic here
for (int i = 0; i < alcohol.size(); i++) {
final String tempName = alcohol.get(i).get("Name").toString();
String tempPrice = alcohol.get(i).get("Price").toString();
String tempQuantity = alcohol.get(i).get("Quantity").toString();
String tempSize = alcohol.get(i).get("Container_Size").toString();
String tempABV = alcohol.get(i).get("ABV").toString();
String tempType = alcohol.get(i).get("Type_Alcohol").toString();
// ParseObject tempStore = alcohol.get(i).getParseObject("Store");
final String tempAlcoholID = alcohol.get(i).getObjectId().toString();
System.out.println(tempName);
if (tempType.equalsIgnoreCase("Beer")) {
Beer tempBeer = new Beer(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempBeer), "1", tempPrice, tempQuantity, al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Gin")) {
Gin tempGin = new Gin(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempGin), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Rum")) {
Rum tempRum = new Rum(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempRum), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Tequila")) {
Tequila tempTequila = new Tequila(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempTequila), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Vodka")) {
Vodka tempVodka = new Vodka(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempVodka), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Whisky") || tempType.equalsIgnoreCase("Whiskey")) {
Whisky tempWhisky = new Whisky(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempWhisky), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Wine")) {
Wine tempWine = new Wine(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempWine), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
}
adapter.addDeals(tempType);
}
} else {
// handle Parse Exception here
System.out.println("Parse Error!");
}
adapter.notifyDataSetChanged();
}
});
}
}
//
// Get the stores from the Parse database
public void getStores(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("Store");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> store, ParseException e) {
if (e == null) {
// your logic here
for (int i = 0; i < store.size(); i++) {
storeHolder.add(store.get(i));
String tempName = store.get(i).get("Store_Name").toString();
String tempAddress = store.get(i).get("Address").toString();
String tempPhone = store.get(i).get("Phone").toString();
// GeoPoint
ParseGeoPoint tempGeoPoint = store.get(i).getParseGeoPoint("LatLng");
LatLng tempLatLng = new LatLng(tempGeoPoint.getLatitude(), tempGeoPoint.getLongitude());
String tempMonday = store.get(i).get("Monday").toString();
String tempTuesday = store.get(i).get("Tuesday").toString();
String tempWednesday = store.get(i).get("Wednesday").toString();
String tempThursday = store.get(i).get("Thursday").toString();
String tempFriday = store.get(i).get("Friday").toString();
String tempSaturday = store.get(i).get("Saturday").toString();
String tempSunday = store.get(i).get("Sunday").toString();
Boolean tempHas_Beer = (Boolean) store.get(i).get("Has_Beer");
Boolean tempHas_Liquor = (Boolean) store.get(i).get("Has_Liquor");
Boolean tempHas_Wine = (Boolean) store.get(i).get("Has_Wine");
String tempID = store.get(i).getObjectId();
System.out.println("Store id: " + tempID + "Name: " + tempName + " Address: " + tempAddress + " Phone: " + tempPhone);
Store tempStore = new Store(tempID, tempAddress, tempHas_Beer, tempHas_Liquor, tempHas_Wine, tempPhone, tempName, tempLatLng, tempMonday, tempTuesday, tempWednesday, tempThursday, tempFriday, tempSaturday, tempSunday);
al_Stores.add(tempStore);
}
} else {
// handle Parse Exception here
System.out.println("Parse Error!");
}
getDeals();
}
});
}
public void updateStoreDistances(){
DecimalFormat df = new DecimalFormat("#.0");
for(Deal deal: al_testDeals){
if(deal.getStore().getStore_loc() != null){
double distance_meters = userLocation.distanceTo(deal.getStore().getStore_loc());
double distance_miles = distance_meters * 0.00062137;
deal.setDistance_from_user(df.format(distance_miles) + " mi");
}
}
Log.d(LOG_TAG, "Updated Store Distances!");
adapter.notifyDataSetChanged();
}
public String convert_Militiers_to_Liters(String size){
if(size.equalsIgnoreCase("1000")){
return "1 L";
}
else if(size.equalsIgnoreCase("1750")){
return "1.75 L";
}
return size + " ml";
}
public void update_Location_Alert(Location loc){
Log.d(LOG_TAG, "Updating Location Alert");
if(loc == null){
Log.d(LOG_TAG, "Update Location Alert: Location not found");
// btn_location_status.setVisibility(View.VISIBLE);
Toast.makeText(Search.this, "Location not found! Ensure Location Services & Network is enabled", Toast.LENGTH_LONG).show();
}
else{
Log.d(LOG_TAG, "Update Location Alert: Location found!");
// btn_location_status.setVisibility(View.GONE);
updateStoreDistances();
}
}
@Override
protected void onResume() {
super.onResume();
// Other onResume() code here
if (!mIsReceiverRegistered) {
if (mReceiver == null)
mReceiver = new LocationBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
mIsReceiverRegistered = true;
}
if (!mIsReceiverRegistered_Internet) {
if (mReceiver_Internet == null)
mReceiver_Internet = new InternetBroadcastReceiver();
registerReceiver(mReceiver_Internet, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
mIsReceiverRegistered_Internet = true;
}
}
@Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(mReceiver);
mReceiver = null;
mIsReceiverRegistered = false;
}
if (mIsReceiverRegistered_Internet) {
unregisterReceiver(mReceiver_Internet);
mReceiver_Internet = null;
mIsReceiverRegistered_Internet = false;
}
// Other onPause() code here
}
// used to listen for intents which are sent after a task was
// successfully processed
// Need to make it so it updates the distances if the location is already enabled/found for the first time
// I keep having to toggle the location at least once in order for it to update
private class LocationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LocationHandler.LocationResult locationResult = new LocationHandler.LocationResult(){
@Override
public void gotLocation(Location location){
//Got the location!
// Location was not found... Should display something to the user or try again
if(location == null){
Log.d(LOG_TAG, "Broadcast Receiver: Location not found");
}
else{
Log.d(LOG_TAG, "Broadcast Receiver: Location found!");
// btn_location_status.setVisibility(View.GONE);
//
userLocation = location;
// updateStoreDistances();
System.out.println("Is userLocation null: " + userLocation == null);
Search.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
update_Location_Alert(userLocation);
}
});
}
}
};
myLocation.getLocation(Search.this, locationResult);
// update_Location_Alert(userLocation);
}
}
// Need to update data if it is stale!
private class InternetBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
is_Connected_To_Internet = internet.networkCheck();
if(is_Connected_To_Internet){
// btn_network_status.setVisibility(View.GONE);
Log.d(LOG_TAG, "Internet Broadcast: Connected!");
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
// Wifi is connected
Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));
if(adapter.getCount() < 1) {
getStores();
}
}
}
else{
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
// btn_network_status.setVisibility(View.VISIBLE);
Log.d(LOG_TAG, "Internet Broadcast: Not Connected!");
}
}
}
} | mthor1234/Boozl | Search.java | 7,351 | // ParseObject tempStore = alcohol.get(i).getParseObject("Store"); | line_comment | nl | package com.crash.boozl.boozl.code;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.crash.boozl.boozl.code.Alcohols.Beer;
import com.crash.boozl.boozl.code.Alcohols.Gin;
import com.crash.boozl.boozl.code.Alcohols.Rum;
import com.crash.boozl.boozl.code.Alcohols.Tequila;
import com.crash.boozl.boozl.code.Alcohols.Vodka;
import com.crash.boozl.boozl.code.Alcohols.Whisky;
import com.crash.boozl.boozl.code.Alcohols.Wine;
import com.google.android.gms.maps.model.LatLng;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Search extends FragmentActivity {
private DrawerLayout mDrawerLayout;
RelativeLayout mDockLayout;
ImageView search_menu, searchCancel;
ListView lv_Results;
ImageButton menu;
// Gridview variables
GridView gv_alcoholType;
RadioGroup rg_display, rg_sort;
Switch switch_list_map;
Search search;
TextView activity_description;
Button btn_network_status, btn_location_status;
Location userLocation = null;
LocationHandler myLocation;
public boolean is_Connected_To_Internet = false;
boolean mIsReceiverRegistered_Internet = false;
InternetBroadcastReceiver mReceiver_Internet = null;
InternetHandler internet;
boolean mIsReceiverRegistered = false;
LocationBroadcastReceiver mReceiver = null;
final ArrayList<Deal> al_testDeals = new ArrayList<Deal>();
public static FragmentManager fragment_manager;
Map map;
String LOG_TAG = Search.class.getSimpleName();
Fragment_Deal_Info fragment_deal_info;
Fragment_Store_Info fragment_store_info;
AutoCompleteTextView autocompletetv_Search;
// Used to populate each different gridview on the DrawerLayout
ArrayList<Item> gridItems_alcoholType = new ArrayList<Item>();
ArrayList<Store> al_Stores = new ArrayList<Store>();
ArrayList<ParseObject> storeHolder = new ArrayList<ParseObject>();
CustomListViewAdapter adapter;
// Creates a custom GridView adapter that is applied to each adapter
CustomGridViewAdapter customGridViewAdapter_Alcohol;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
System.out.println("No saved instance");
fragment_deal_info = new Fragment_Deal_Info();
fragment_deal_info.setActivity_search(this);
fragment_store_info = new Fragment_Store_Info();
fragment_store_info.setActivity_search(this);
}
else {
if((Fragment_Deal_Info) getFragmentManager().findFragmentByTag("Deal_Info") != null) {
fragment_deal_info = (Fragment_Deal_Info) getFragmentManager().findFragmentByTag("Deal_Info");
fragment_store_info = (Fragment_Store_Info) getFragmentManager().findFragmentByTag("Store_Info");
}
else{
fragment_deal_info = new Fragment_Deal_Info();
fragment_deal_info.setActivity_search(this);
fragment_store_info = new Fragment_Store_Info();
fragment_store_info.setActivity_search(this);
}
}
// Enable Local Datastore.
// Sometimes get an error here! Not sure why... It happens after going to the Galaxy Main Screen then re opening the app
Parse.enableLocalDatastore(this);
Parse.initialize(this, "ibsGWbLLA1BsbYWCd163g2vVJMd9LrhE6vmIovj2", "Vy8jgDckbEu3D5258KJSmSftShHqGHukeMtWliHs");
setContentView(R.layout.activity_search);
search_menu = (ImageView) findViewById(R.id.menu_imageView);
searchCancel = (ImageView) findViewById((R.id.imgbtn_search_cancel));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDockLayout = (RelativeLayout) findViewById(R.id.dockedLayout);
lv_Results = (ListView) findViewById(R.id.lv_results);
gv_alcoholType = (GridView) findViewById(R.id.gridview_alcohol_selection);
// rg_display = (RadioGroup) findViewById(R.id.rg_display);
rg_sort = (RadioGroup) findViewById(R.id.rg_sort);
switch_list_map = (Switch) findViewById(R.id.switch_toggle);
autocompletetv_Search = (AutoCompleteTextView) findViewById(R.id.autocompletetv_search);
activity_description = (TextView) findViewById(R.id.zone_name);
btn_network_status = (Button) findViewById(R.id.btn_network_alert);
btn_location_status = (Button) findViewById(R.id.btn_location_alert);
// menu = (ImageButton) findViewById(R.id.imgbtn_menu);
search = this;
map = new Map();
map.setSearch(this);
fragment_manager = getFragmentManager();
map = new Map();
adapter = new CustomListViewAdapter(search, al_testDeals);
lv_Results.setAdapter(adapter);
internet = new InternetHandler(this, this);
is_Connected_To_Internet = internet.networkCheck();
if(is_Connected_To_Internet){
// getStores();
}
else{
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
}
// Get the deals from Parse database and populate the deal listview
// getDeals();
LocationHandler.LocationResult locationResult = new LocationHandler.LocationResult(){
@Override
public void gotLocation(Location location) {
//Got the location!
// Location was not found... Should display something to the user or try again
Log.d(LOG_TAG, "Search is Finding the Location!");
if (location == null) {
Log.d(LOG_TAG, "Location not found");
userLocation = location;
} else {
Log.d(LOG_TAG, "Location found!");
userLocation = location;
System.out.println("Is userLocation null: " + userLocation == null);
Search.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
update_Location_Alert(userLocation);
}
});
userLocation = location;
}
}
};
//
//
update_Location_Alert(userLocation);
myLocation = new LocationHandler(this, this);
myLocation.getLocation(this, locationResult);
// Create the grid view icons
// Alcohol Type Icons
Bitmap beerIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.beer_icon);
Bitmap wineIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.wine_icon);
Bitmap vodkaIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.vodka_icon);
Bitmap whiskyIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.whisky_icon);
Bitmap tequilaIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.tequila_icon);
Bitmap ginIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
final Bitmap rumIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
Bitmap kegIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
Bitmap storeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.other_icon);
// Sort by Icons
Bitmap a_to_zIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.a_to_z_icon);
Bitmap sizeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.size_icon);
Bitmap priceIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.price_icon);
Bitmap distanceIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.distance_icon);
// Add the icons and text to the different grid views
// Alcohol Type
gridItems_alcoholType.add(new Item(beerIcon, "Beer"));
gridItems_alcoholType.add(new Item(wineIcon, "Wine"));
gridItems_alcoholType.add(new Item(vodkaIcon, "Vodka"));
gridItems_alcoholType.add(new Item(whiskyIcon, "Whisky"));
gridItems_alcoholType.add(new Item(tequilaIcon, "Tequila"));
gridItems_alcoholType.add(new Item(ginIcon, "Gin"));
gridItems_alcoholType.add(new Item(rumIcon, "Rum"));
gridItems_alcoholType.add(new Item(kegIcon, "Keg"));
gridItems_alcoholType.add(new Item(storeIcon, "Store"));
search_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(mDockLayout);
}
});
// searchCancel is used to remove all the text the user has used to search.... Prevents the user from having to backspace
//Throughout the entire text in order to clear the search
searchCancel.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
autocompletetv_Search.setText("");
}
});
btn_network_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(Search.this);
dialog.setMessage(Search.this.getResources().getString(R.string.network_not_enabled));
dialog.setPositiveButton(Search.this.getResources().getString(R.string.open_network_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// Wong INTENT!
Intent myIntent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
Search.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(Search.this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
});
btn_location_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
customGridViewAdapter_Alcohol = new CustomGridViewAdapter(this, R.layout.row_grid, gridItems_alcoholType, this);
gv_alcoholType.setAdapter(customGridViewAdapter_Alcohol);
for(int i = 0; i < gridItems_alcoholType.size(); i++){
gridItems_alcoholType.get(i).toggleCheck();
}
switch_list_map.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked){
if(fragment_deal_info.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_deal_info);
transaction.commit();
}
else if(fragment_store_info.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_store_info);
transaction.commit();
}
else if(map.isAdded()) {
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(map);
transaction.commit();
}
activity_description.setText("Results");
}
else{
if (fragment_deal_info.isAdded()) {
System.out.println("Deal info is currently visible!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
} else if (fragment_store_info.isAdded()) {
System.out.println("Store info is currently visible!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
} else if (!map.isAdded()) {
System.out.println("Map has not been added yet!");
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
transaction.addToBackStack(null);
map.setSearch(search);
transaction.commit();
}
activity_description.setText("Results");
}
}
});
rg_sort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rb_a_to_z) {
adapter.sortDeals(R.id.rb_a_to_z);
} else if (checkedId == R.id.rb_price) {
adapter.sortDeals(R.id.rb_price);
} else if (checkedId == R.id.rb_size) {
adapter.sortDeals(R.id.rb_size);
} else if (checkedId == R.id.rb_distance) {
adapter.sortDeals(R.id.rb_distance);
}
}
});
// Adds a text watcher to the AutoComplete Search bar so that the results can be filtered out
autocompletetv_Search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = autocompletetv_Search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
adapter.sortDeals(rg_sort.getCheckedRadioButtonId());
// Update the map
if (search.map.isResumed()) {
map.showDeals();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
autocompletetv_Search.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
mDrawerLayout.closeDrawer(mDockLayout);
// Clicking the autocomplete search accessory button will take you to the Map view with the deals if the Mapview radio button is currently checked
if(fragment_store_info.isAdded() || fragment_deal_info.isAdded() && switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.replace(R.id.fragment_holder, map);
map.setSearch(search);
transaction.commit();
}
// Otherwise it will take you to the Search activity with the List view displaying all the deals
else if(fragment_deal_info.isAdded() && !switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_deal_info);
transaction.commit();
}
else if(fragment_store_info.isAdded() && !switch_list_map.isChecked()){
FragmentTransaction transaction = fragment_manager.beginTransaction();
transaction.remove(fragment_store_info);
transaction.commit();
}
handled = true;
}
return handled;
}
});
}
@Override
protected void onDestroy() {
System.out.println("Destroying Search");
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_settings, popup.getMenu());
popup.show();
}
@Override
public void onBackPressed() {
if(fragment_manager.getBackStackEntryCount() != 0) {
fragment_manager.popBackStack();
} else {
activity_description.setText("Results");
super.onBackPressed();
}
}
public void getDeals() {
System.out.println("getDeals called!");
System.out.println("Size of stores is: " + al_Stores.size());
for (int z = 0; z < al_Stores.size(); z++) {
final int j = z;
ParseQuery<ParseObject> query = ParseQuery.getQuery("Alcohol").whereEqualTo("Store", storeHolder.get(z));
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> alcohol, ParseException e) {
if (e == null) {
ArrayList<ParseObject> tempIDHolder = new ArrayList<ParseObject>();
// your logic here
for (int i = 0; i < alcohol.size(); i++) {
final String tempName = alcohol.get(i).get("Name").toString();
String tempPrice = alcohol.get(i).get("Price").toString();
String tempQuantity = alcohol.get(i).get("Quantity").toString();
String tempSize = alcohol.get(i).get("Container_Size").toString();
String tempABV = alcohol.get(i).get("ABV").toString();
String tempType = alcohol.get(i).get("Type_Alcohol").toString();
// ParseObject tempStore<SUF>
final String tempAlcoholID = alcohol.get(i).getObjectId().toString();
System.out.println(tempName);
if (tempType.equalsIgnoreCase("Beer")) {
Beer tempBeer = new Beer(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempBeer), "1", tempPrice, tempQuantity, al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Gin")) {
Gin tempGin = new Gin(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempGin), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Rum")) {
Rum tempRum = new Rum(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempRum), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Tequila")) {
Tequila tempTequila = new Tequila(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempTequila), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Vodka")) {
Vodka tempVodka = new Vodka(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempVodka), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Whisky") || tempType.equalsIgnoreCase("Whiskey")) {
Whisky tempWhisky = new Whisky(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempWhisky), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
} else if (tempType.equalsIgnoreCase("Wine")) {
Wine tempWine = new Wine(tempABV + "% abv", "", "", tempName, tempType, search);
al_testDeals.add(new Deal((tempWine), "1", tempPrice, convert_Militiers_to_Liters(tempSize), al_Stores.get(j), tempSize));
}
adapter.addDeals(tempType);
}
} else {
// handle Parse Exception here
System.out.println("Parse Error!");
}
adapter.notifyDataSetChanged();
}
});
}
}
//
// Get the stores from the Parse database
public void getStores(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("Store");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> store, ParseException e) {
if (e == null) {
// your logic here
for (int i = 0; i < store.size(); i++) {
storeHolder.add(store.get(i));
String tempName = store.get(i).get("Store_Name").toString();
String tempAddress = store.get(i).get("Address").toString();
String tempPhone = store.get(i).get("Phone").toString();
// GeoPoint
ParseGeoPoint tempGeoPoint = store.get(i).getParseGeoPoint("LatLng");
LatLng tempLatLng = new LatLng(tempGeoPoint.getLatitude(), tempGeoPoint.getLongitude());
String tempMonday = store.get(i).get("Monday").toString();
String tempTuesday = store.get(i).get("Tuesday").toString();
String tempWednesday = store.get(i).get("Wednesday").toString();
String tempThursday = store.get(i).get("Thursday").toString();
String tempFriday = store.get(i).get("Friday").toString();
String tempSaturday = store.get(i).get("Saturday").toString();
String tempSunday = store.get(i).get("Sunday").toString();
Boolean tempHas_Beer = (Boolean) store.get(i).get("Has_Beer");
Boolean tempHas_Liquor = (Boolean) store.get(i).get("Has_Liquor");
Boolean tempHas_Wine = (Boolean) store.get(i).get("Has_Wine");
String tempID = store.get(i).getObjectId();
System.out.println("Store id: " + tempID + "Name: " + tempName + " Address: " + tempAddress + " Phone: " + tempPhone);
Store tempStore = new Store(tempID, tempAddress, tempHas_Beer, tempHas_Liquor, tempHas_Wine, tempPhone, tempName, tempLatLng, tempMonday, tempTuesday, tempWednesday, tempThursday, tempFriday, tempSaturday, tempSunday);
al_Stores.add(tempStore);
}
} else {
// handle Parse Exception here
System.out.println("Parse Error!");
}
getDeals();
}
});
}
public void updateStoreDistances(){
DecimalFormat df = new DecimalFormat("#.0");
for(Deal deal: al_testDeals){
if(deal.getStore().getStore_loc() != null){
double distance_meters = userLocation.distanceTo(deal.getStore().getStore_loc());
double distance_miles = distance_meters * 0.00062137;
deal.setDistance_from_user(df.format(distance_miles) + " mi");
}
}
Log.d(LOG_TAG, "Updated Store Distances!");
adapter.notifyDataSetChanged();
}
public String convert_Militiers_to_Liters(String size){
if(size.equalsIgnoreCase("1000")){
return "1 L";
}
else if(size.equalsIgnoreCase("1750")){
return "1.75 L";
}
return size + " ml";
}
public void update_Location_Alert(Location loc){
Log.d(LOG_TAG, "Updating Location Alert");
if(loc == null){
Log.d(LOG_TAG, "Update Location Alert: Location not found");
// btn_location_status.setVisibility(View.VISIBLE);
Toast.makeText(Search.this, "Location not found! Ensure Location Services & Network is enabled", Toast.LENGTH_LONG).show();
}
else{
Log.d(LOG_TAG, "Update Location Alert: Location found!");
// btn_location_status.setVisibility(View.GONE);
updateStoreDistances();
}
}
@Override
protected void onResume() {
super.onResume();
// Other onResume() code here
if (!mIsReceiverRegistered) {
if (mReceiver == null)
mReceiver = new LocationBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
mIsReceiverRegistered = true;
}
if (!mIsReceiverRegistered_Internet) {
if (mReceiver_Internet == null)
mReceiver_Internet = new InternetBroadcastReceiver();
registerReceiver(mReceiver_Internet, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
mIsReceiverRegistered_Internet = true;
}
}
@Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(mReceiver);
mReceiver = null;
mIsReceiverRegistered = false;
}
if (mIsReceiverRegistered_Internet) {
unregisterReceiver(mReceiver_Internet);
mReceiver_Internet = null;
mIsReceiverRegistered_Internet = false;
}
// Other onPause() code here
}
// used to listen for intents which are sent after a task was
// successfully processed
// Need to make it so it updates the distances if the location is already enabled/found for the first time
// I keep having to toggle the location at least once in order for it to update
private class LocationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LocationHandler.LocationResult locationResult = new LocationHandler.LocationResult(){
@Override
public void gotLocation(Location location){
//Got the location!
// Location was not found... Should display something to the user or try again
if(location == null){
Log.d(LOG_TAG, "Broadcast Receiver: Location not found");
}
else{
Log.d(LOG_TAG, "Broadcast Receiver: Location found!");
// btn_location_status.setVisibility(View.GONE);
//
userLocation = location;
// updateStoreDistances();
System.out.println("Is userLocation null: " + userLocation == null);
Search.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
update_Location_Alert(userLocation);
}
});
}
}
};
myLocation.getLocation(Search.this, locationResult);
// update_Location_Alert(userLocation);
}
}
// Need to update data if it is stale!
private class InternetBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
is_Connected_To_Internet = internet.networkCheck();
if(is_Connected_To_Internet){
// btn_network_status.setVisibility(View.GONE);
Log.d(LOG_TAG, "Internet Broadcast: Connected!");
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
// Wifi is connected
Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));
if(adapter.getCount() < 1) {
getStores();
}
}
}
else{
Toast.makeText(Search.this, "No network connection! Enable network connection", Toast.LENGTH_LONG).show();
// btn_network_status.setVisibility(View.VISIBLE);
Log.d(LOG_TAG, "Internet Broadcast: Not Connected!");
}
}
}
} |
209434_1 | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| tbarua1/uy | ServletTest/src/basic/GetParameterValues.java | 364 | /**
* @see HttpServlet#HttpServlet()
*/ | block_comment | nl | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
<SUF>*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
209567_1 | /*
* Copyright 2022 Topicus Onderwijs Eduarte B.V..
*
* 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 nl.topicus.eduarte.model.entities.landelijk;
import javax.persistence.Column;
import javax.persistence.Entity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import nl.topicus.eduarte.model.entities.ICodeNaamEntiteit;
import nl.topicus.eduarte.model.entities.IsViewWhenOnNoise;
import nl.topicus.eduarte.model.entities.begineinddatum.BeginEinddatumLandelijkEntiteit;
/**
* Landentabel uit de basisadministratie Persoonsgegevens en Reisdocumenten van
* het Ministerie van Binnenlandse Zaken en Koninkrijksrelaties. Dit betreft
* tabel 34 van het GBA te vinden op <a href=
* "http://www.bprbzk.nl/GBA/Informatiebank/Procedures/Landelijke_tabellen/Landelijke_Tabellen_32_t_m_56_excl_35"
* >bprbzk.nl</a>
*
*/
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Landelijk")
@IsViewWhenOnNoise
public class Land extends BeginEinddatumLandelijkEntiteit implements ICodeNaamEntiteit {
public static final String CODE_NEDERLAND = "6030";
public static final String CODE_BELGIE = "5010";
public static final String CODE_LUXEMBURG = "6018";
public static final String CODE_DUITSLAND = "9089";
@Column(length = 4, nullable = false)
private String code;
@Column(length = 100, nullable = false)
private String naam;
@Column(length = 2, nullable = true)
private String isoCode;
@Override
public String getCode() {
return code;
}
@Override
public void setCode(String code) {
this.code = code;
}
@Override
public String getNaam() {
return naam;
}
@Override
public void setNaam(String naam) {
this.naam = naam;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
}
| franz1981/tribe-krd-quarkus | src/main/java/nl/topicus/eduarte/model/entities/landelijk/Land.java | 759 | /**
* Landentabel uit de basisadministratie Persoonsgegevens en Reisdocumenten van
* het Ministerie van Binnenlandse Zaken en Koninkrijksrelaties. Dit betreft
* tabel 34 van het GBA te vinden op <a href=
* "http://www.bprbzk.nl/GBA/Informatiebank/Procedures/Landelijke_tabellen/Landelijke_Tabellen_32_t_m_56_excl_35"
* >bprbzk.nl</a>
*
*/ | block_comment | nl | /*
* Copyright 2022 Topicus Onderwijs Eduarte B.V..
*
* 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 nl.topicus.eduarte.model.entities.landelijk;
import javax.persistence.Column;
import javax.persistence.Entity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import nl.topicus.eduarte.model.entities.ICodeNaamEntiteit;
import nl.topicus.eduarte.model.entities.IsViewWhenOnNoise;
import nl.topicus.eduarte.model.entities.begineinddatum.BeginEinddatumLandelijkEntiteit;
/**
* Landentabel uit de<SUF>*/
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Landelijk")
@IsViewWhenOnNoise
public class Land extends BeginEinddatumLandelijkEntiteit implements ICodeNaamEntiteit {
public static final String CODE_NEDERLAND = "6030";
public static final String CODE_BELGIE = "5010";
public static final String CODE_LUXEMBURG = "6018";
public static final String CODE_DUITSLAND = "9089";
@Column(length = 4, nullable = false)
private String code;
@Column(length = 100, nullable = false)
private String naam;
@Column(length = 2, nullable = true)
private String isoCode;
@Override
public String getCode() {
return code;
}
@Override
public void setCode(String code) {
this.code = code;
}
@Override
public String getNaam() {
return naam;
}
@Override
public void setNaam(String naam) {
this.naam = naam;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
}
|
209599_4 | /*
* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.didi.virtualapk;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ActivityThread;
import android.app.Application;
import android.app.IActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.IContentProvider;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Singleton;
import com.didi.virtualapk.delegate.ActivityManagerProxy;
import com.didi.virtualapk.delegate.IContentProviderProxy;
import com.didi.virtualapk.delegate.RemoteContentProvider;
import com.didi.virtualapk.internal.ComponentsHandler;
import com.didi.virtualapk.internal.Constants;
import com.didi.virtualapk.internal.LoadedPlugin;
import com.didi.virtualapk.internal.VAInstrumentation;
import com.didi.virtualapk.internal.utils.PluginUtil;
import com.didi.virtualapk.utils.Reflector;
import com.didi.virtualapk.utils.RunUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by renyugang on 16/8/9.
*/
public class PluginManager {
public static final String TAG = Constants.TAG_PREFIX + "PluginManager";
private static volatile PluginManager sInstance = null;
// Context of host app
protected final Context mContext;
protected final Application mApplication;
protected ComponentsHandler mComponentsHandler;
protected final Map<String, LoadedPlugin> mPlugins = new ConcurrentHashMap<>();
protected final List<Callback> mCallbacks = new ArrayList<>();
protected VAInstrumentation mInstrumentation; // Hooked instrumentation
protected IActivityManager mActivityManager; // Hooked IActivityManager binder
protected IContentProvider mIContentProvider; // Hooked IContentProvider binder
public static PluginManager getInstance(Context base) {
if (sInstance == null) {
synchronized (PluginManager.class) {
if (sInstance == null) {
sInstance = createInstance(base);
}
}
}
return sInstance;
}
private static PluginManager createInstance(Context context) {
try {
Bundle metaData = context.getPackageManager()
.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)
.metaData;
if (metaData == null) {
return new PluginManager(context);
}
String factoryClass = metaData.getString("VA_FACTORY");
if (factoryClass == null) {
return new PluginManager(context);
}
PluginManager pluginManager = Reflector.on(factoryClass).method("create", Context.class).call(context);
if (pluginManager != null) {
Log.d(TAG, "Created a instance of " + pluginManager.getClass());
return pluginManager;
}
} catch (Exception e) {
Log.w(TAG, "Created the instance error!", e);
}
return new PluginManager(context);
}
protected PluginManager(Context context) {
if (context instanceof Application) {
this.mApplication = (Application) context;
this.mContext = mApplication.getBaseContext();
} else {
final Context app = context.getApplicationContext();
if (app == null) {
this.mContext = context;
this.mApplication = ActivityThread.currentApplication();
} else {
this.mApplication = (Application) app;
this.mContext = mApplication.getBaseContext();
}
}
mComponentsHandler = createComponentsHandler();
hookCurrentProcess();
}
protected void hookCurrentProcess() {
hookInstrumentationAndHandler();
hookSystemServices();
hookDataBindingUtil();
}
public void init() {
RunUtil.getThreadPool().execute(new Runnable() {
@Override
public void run() {
doInWorkThread();
}
});
}
protected void doInWorkThread() {
}
public Application getHostApplication() {
return this.mApplication;
}
protected ComponentsHandler createComponentsHandler() {
return new ComponentsHandler(this);
}
protected VAInstrumentation createInstrumentation(Instrumentation origin) throws Exception {
return new VAInstrumentation(this, origin);
}
protected ActivityManagerProxy createActivityManagerProxy(IActivityManager origin) throws Exception {
return new ActivityManagerProxy(this, origin);
}
protected LoadedPlugin createLoadedPlugin(File apk) throws Exception {
return new LoadedPlugin(this, this.mContext, apk);
}
protected void hookDataBindingUtil() {
Reflector.QuietReflector reflector = Reflector.QuietReflector.on("android.databinding.DataBindingUtil").field("sMapper");
Object old = reflector.get();
if (old != null) {
try {
Callback callback = Reflector.on("android.databinding.DataBinderMapperProxy").constructor().newInstance();
reflector.set(callback);
addCallback(callback);
Log.d(TAG, "hookDataBindingUtil succeed : " + callback);
} catch (Reflector.ReflectedException e) {
Log.w(TAG, e);
}
}
}
public void addCallback(Callback callback) {
if (callback == null) {
return;
}
synchronized (mCallbacks) {
if (mCallbacks.contains(callback)) {
throw new RuntimeException("Already added " + callback + "!");
}
mCallbacks.add(callback);
}
}
public void removeCallback(Callback callback) {
synchronized (mCallbacks) {
mCallbacks.remove(callback);
}
}
/**
* hookSystemServices, but need to compatible with Android O in future.
*/
protected void hookSystemServices() {
try {
Singleton<IActivityManager> defaultSingleton;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
defaultSingleton = Reflector.on(ActivityManager.class).field("IActivityManagerSingleton").get();
} else {
defaultSingleton = Reflector.on(ActivityManagerNative.class).field("gDefault").get();
}
IActivityManager origin = defaultSingleton.get();
IActivityManager activityManagerProxy = (IActivityManager) Proxy.newProxyInstance(mContext.getClassLoader(), new Class[] { IActivityManager.class },
createActivityManagerProxy(origin));
// Hook IActivityManager from ActivityManagerNative
Reflector.with(defaultSingleton).field("mInstance").set(activityManagerProxy);
if (defaultSingleton.get() == activityManagerProxy) {
this.mActivityManager = activityManagerProxy;
Log.d(TAG, "hookSystemServices succeed : " + mActivityManager);
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
protected void hookInstrumentationAndHandler() {
try {
ActivityThread activityThread = ActivityThread.currentActivityThread();
Instrumentation baseInstrumentation = activityThread.getInstrumentation();
// if (baseInstrumentation.getClass().getName().contains("lbe")) {
// // reject executing in paralell space, for example, lbe.
// System.exit(0);
// }
final VAInstrumentation instrumentation = createInstrumentation(baseInstrumentation);
Reflector.with(activityThread).field("mInstrumentation").set(instrumentation);
Handler mainHandler = Reflector.with(activityThread).method("getHandler").call();
Reflector.with(mainHandler).field("mCallback").set(instrumentation);
this.mInstrumentation = instrumentation;
Log.d(TAG, "hookInstrumentationAndHandler succeed : " + mInstrumentation);
} catch (Exception e) {
Log.w(TAG, e);
}
}
protected void hookIContentProviderAsNeeded() {
Uri uri = Uri.parse(RemoteContentProvider.getUri(mContext));
mContext.getContentResolver().call(uri, "wakeup", null, null);
try {
Field authority = null;
Field provider = null;
ActivityThread activityThread = ActivityThread.currentActivityThread();
Map providerMap = Reflector.with(activityThread).field("mProviderMap").get();
Iterator iter = providerMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
String auth;
if (key instanceof String) {
auth = (String) key;
} else {
if (authority == null) {
authority = key.getClass().getDeclaredField("authority");
authority.setAccessible(true);
}
auth = (String) authority.get(key);
}
if (auth.equals(RemoteContentProvider.getAuthority(mContext))) {
if (provider == null) {
provider = val.getClass().getDeclaredField("mProvider");
provider.setAccessible(true);
}
IContentProvider rawProvider = (IContentProvider) provider.get(val);
IContentProvider proxy = IContentProviderProxy.newInstance(mContext, rawProvider);
mIContentProvider = proxy;
Log.d(TAG, "hookIContentProvider succeed : " + mIContentProvider);
break;
}
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
/**
* load a plugin into memory, then invoke it's Application.
* @param apk the file of plugin, should end with .apk
* @throws Exception
*/
public void loadPlugin(File apk) throws Exception {
if (null == apk) {
throw new IllegalArgumentException("error : apk is null.");
}
if (!apk.exists()) {
// throw the FileNotFoundException by opening a stream.
InputStream in = new FileInputStream(apk);
in.close();
}
LoadedPlugin plugin = createLoadedPlugin(apk);
if (null == plugin) {
throw new RuntimeException("Can't load plugin which is invalid: " + apk.getAbsolutePath());
}
this.mPlugins.put(plugin.getPackageName(), plugin);
synchronized (mCallbacks) {
for (int i = 0; i < mCallbacks.size(); i++) {
mCallbacks.get(i).onAddedLoadedPlugin(plugin);
}
}
}
public LoadedPlugin getLoadedPlugin(Intent intent) {
return getLoadedPlugin(PluginUtil.getComponent(intent));
}
public LoadedPlugin getLoadedPlugin(ComponentName component) {
if (component == null) {
return null;
}
return this.getLoadedPlugin(component.getPackageName());
}
public LoadedPlugin getLoadedPlugin(String packageName) {
return this.mPlugins.get(packageName);
}
public List<LoadedPlugin> getAllLoadedPlugins() {
List<LoadedPlugin> list = new ArrayList<>();
list.addAll(mPlugins.values());
return list;
}
public Context getHostContext() {
return this.mContext;
}
public VAInstrumentation getInstrumentation() {
return this.mInstrumentation;
}
public IActivityManager getActivityManager() {
return this.mActivityManager;
}
public synchronized IContentProvider getIContentProvider() {
if (mIContentProvider == null) {
hookIContentProviderAsNeeded();
}
return mIContentProvider;
}
public ComponentsHandler getComponentsHandler() {
return mComponentsHandler;
}
public ResolveInfo resolveActivity(Intent intent) {
return this.resolveActivity(intent, 0);
}
public ResolveInfo resolveActivity(Intent intent, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ResolveInfo resolveInfo = plugin.resolveActivity(intent, flags);
if (null != resolveInfo) {
return resolveInfo;
}
}
return null;
}
public ResolveInfo resolveService(Intent intent, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ResolveInfo resolveInfo = plugin.resolveService(intent, flags);
if (null != resolveInfo) {
return resolveInfo;
}
}
return null;
}
public ProviderInfo resolveContentProvider(String name, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ProviderInfo providerInfo = plugin.resolveContentProvider(name, flags);
if (null != providerInfo) {
return providerInfo;
}
}
return null;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryIntentActivities(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryIntentServices(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryBroadcastReceivers(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
public interface Callback {
void onAddedLoadedPlugin(LoadedPlugin plugin);
}
} | didi/VirtualAPK | CoreLibrary/src/main/java/com/didi/virtualapk/PluginManager.java | 3,814 | // Hooked IContentProvider binder | line_comment | nl | /*
* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.didi.virtualapk;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ActivityThread;
import android.app.Application;
import android.app.IActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.IContentProvider;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Singleton;
import com.didi.virtualapk.delegate.ActivityManagerProxy;
import com.didi.virtualapk.delegate.IContentProviderProxy;
import com.didi.virtualapk.delegate.RemoteContentProvider;
import com.didi.virtualapk.internal.ComponentsHandler;
import com.didi.virtualapk.internal.Constants;
import com.didi.virtualapk.internal.LoadedPlugin;
import com.didi.virtualapk.internal.VAInstrumentation;
import com.didi.virtualapk.internal.utils.PluginUtil;
import com.didi.virtualapk.utils.Reflector;
import com.didi.virtualapk.utils.RunUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by renyugang on 16/8/9.
*/
public class PluginManager {
public static final String TAG = Constants.TAG_PREFIX + "PluginManager";
private static volatile PluginManager sInstance = null;
// Context of host app
protected final Context mContext;
protected final Application mApplication;
protected ComponentsHandler mComponentsHandler;
protected final Map<String, LoadedPlugin> mPlugins = new ConcurrentHashMap<>();
protected final List<Callback> mCallbacks = new ArrayList<>();
protected VAInstrumentation mInstrumentation; // Hooked instrumentation
protected IActivityManager mActivityManager; // Hooked IActivityManager binder
protected IContentProvider mIContentProvider; // Hooked IContentProvider<SUF>
public static PluginManager getInstance(Context base) {
if (sInstance == null) {
synchronized (PluginManager.class) {
if (sInstance == null) {
sInstance = createInstance(base);
}
}
}
return sInstance;
}
private static PluginManager createInstance(Context context) {
try {
Bundle metaData = context.getPackageManager()
.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)
.metaData;
if (metaData == null) {
return new PluginManager(context);
}
String factoryClass = metaData.getString("VA_FACTORY");
if (factoryClass == null) {
return new PluginManager(context);
}
PluginManager pluginManager = Reflector.on(factoryClass).method("create", Context.class).call(context);
if (pluginManager != null) {
Log.d(TAG, "Created a instance of " + pluginManager.getClass());
return pluginManager;
}
} catch (Exception e) {
Log.w(TAG, "Created the instance error!", e);
}
return new PluginManager(context);
}
protected PluginManager(Context context) {
if (context instanceof Application) {
this.mApplication = (Application) context;
this.mContext = mApplication.getBaseContext();
} else {
final Context app = context.getApplicationContext();
if (app == null) {
this.mContext = context;
this.mApplication = ActivityThread.currentApplication();
} else {
this.mApplication = (Application) app;
this.mContext = mApplication.getBaseContext();
}
}
mComponentsHandler = createComponentsHandler();
hookCurrentProcess();
}
protected void hookCurrentProcess() {
hookInstrumentationAndHandler();
hookSystemServices();
hookDataBindingUtil();
}
public void init() {
RunUtil.getThreadPool().execute(new Runnable() {
@Override
public void run() {
doInWorkThread();
}
});
}
protected void doInWorkThread() {
}
public Application getHostApplication() {
return this.mApplication;
}
protected ComponentsHandler createComponentsHandler() {
return new ComponentsHandler(this);
}
protected VAInstrumentation createInstrumentation(Instrumentation origin) throws Exception {
return new VAInstrumentation(this, origin);
}
protected ActivityManagerProxy createActivityManagerProxy(IActivityManager origin) throws Exception {
return new ActivityManagerProxy(this, origin);
}
protected LoadedPlugin createLoadedPlugin(File apk) throws Exception {
return new LoadedPlugin(this, this.mContext, apk);
}
protected void hookDataBindingUtil() {
Reflector.QuietReflector reflector = Reflector.QuietReflector.on("android.databinding.DataBindingUtil").field("sMapper");
Object old = reflector.get();
if (old != null) {
try {
Callback callback = Reflector.on("android.databinding.DataBinderMapperProxy").constructor().newInstance();
reflector.set(callback);
addCallback(callback);
Log.d(TAG, "hookDataBindingUtil succeed : " + callback);
} catch (Reflector.ReflectedException e) {
Log.w(TAG, e);
}
}
}
public void addCallback(Callback callback) {
if (callback == null) {
return;
}
synchronized (mCallbacks) {
if (mCallbacks.contains(callback)) {
throw new RuntimeException("Already added " + callback + "!");
}
mCallbacks.add(callback);
}
}
public void removeCallback(Callback callback) {
synchronized (mCallbacks) {
mCallbacks.remove(callback);
}
}
/**
* hookSystemServices, but need to compatible with Android O in future.
*/
protected void hookSystemServices() {
try {
Singleton<IActivityManager> defaultSingleton;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
defaultSingleton = Reflector.on(ActivityManager.class).field("IActivityManagerSingleton").get();
} else {
defaultSingleton = Reflector.on(ActivityManagerNative.class).field("gDefault").get();
}
IActivityManager origin = defaultSingleton.get();
IActivityManager activityManagerProxy = (IActivityManager) Proxy.newProxyInstance(mContext.getClassLoader(), new Class[] { IActivityManager.class },
createActivityManagerProxy(origin));
// Hook IActivityManager from ActivityManagerNative
Reflector.with(defaultSingleton).field("mInstance").set(activityManagerProxy);
if (defaultSingleton.get() == activityManagerProxy) {
this.mActivityManager = activityManagerProxy;
Log.d(TAG, "hookSystemServices succeed : " + mActivityManager);
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
protected void hookInstrumentationAndHandler() {
try {
ActivityThread activityThread = ActivityThread.currentActivityThread();
Instrumentation baseInstrumentation = activityThread.getInstrumentation();
// if (baseInstrumentation.getClass().getName().contains("lbe")) {
// // reject executing in paralell space, for example, lbe.
// System.exit(0);
// }
final VAInstrumentation instrumentation = createInstrumentation(baseInstrumentation);
Reflector.with(activityThread).field("mInstrumentation").set(instrumentation);
Handler mainHandler = Reflector.with(activityThread).method("getHandler").call();
Reflector.with(mainHandler).field("mCallback").set(instrumentation);
this.mInstrumentation = instrumentation;
Log.d(TAG, "hookInstrumentationAndHandler succeed : " + mInstrumentation);
} catch (Exception e) {
Log.w(TAG, e);
}
}
protected void hookIContentProviderAsNeeded() {
Uri uri = Uri.parse(RemoteContentProvider.getUri(mContext));
mContext.getContentResolver().call(uri, "wakeup", null, null);
try {
Field authority = null;
Field provider = null;
ActivityThread activityThread = ActivityThread.currentActivityThread();
Map providerMap = Reflector.with(activityThread).field("mProviderMap").get();
Iterator iter = providerMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
String auth;
if (key instanceof String) {
auth = (String) key;
} else {
if (authority == null) {
authority = key.getClass().getDeclaredField("authority");
authority.setAccessible(true);
}
auth = (String) authority.get(key);
}
if (auth.equals(RemoteContentProvider.getAuthority(mContext))) {
if (provider == null) {
provider = val.getClass().getDeclaredField("mProvider");
provider.setAccessible(true);
}
IContentProvider rawProvider = (IContentProvider) provider.get(val);
IContentProvider proxy = IContentProviderProxy.newInstance(mContext, rawProvider);
mIContentProvider = proxy;
Log.d(TAG, "hookIContentProvider succeed : " + mIContentProvider);
break;
}
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
/**
* load a plugin into memory, then invoke it's Application.
* @param apk the file of plugin, should end with .apk
* @throws Exception
*/
public void loadPlugin(File apk) throws Exception {
if (null == apk) {
throw new IllegalArgumentException("error : apk is null.");
}
if (!apk.exists()) {
// throw the FileNotFoundException by opening a stream.
InputStream in = new FileInputStream(apk);
in.close();
}
LoadedPlugin plugin = createLoadedPlugin(apk);
if (null == plugin) {
throw new RuntimeException("Can't load plugin which is invalid: " + apk.getAbsolutePath());
}
this.mPlugins.put(plugin.getPackageName(), plugin);
synchronized (mCallbacks) {
for (int i = 0; i < mCallbacks.size(); i++) {
mCallbacks.get(i).onAddedLoadedPlugin(plugin);
}
}
}
public LoadedPlugin getLoadedPlugin(Intent intent) {
return getLoadedPlugin(PluginUtil.getComponent(intent));
}
public LoadedPlugin getLoadedPlugin(ComponentName component) {
if (component == null) {
return null;
}
return this.getLoadedPlugin(component.getPackageName());
}
public LoadedPlugin getLoadedPlugin(String packageName) {
return this.mPlugins.get(packageName);
}
public List<LoadedPlugin> getAllLoadedPlugins() {
List<LoadedPlugin> list = new ArrayList<>();
list.addAll(mPlugins.values());
return list;
}
public Context getHostContext() {
return this.mContext;
}
public VAInstrumentation getInstrumentation() {
return this.mInstrumentation;
}
public IActivityManager getActivityManager() {
return this.mActivityManager;
}
public synchronized IContentProvider getIContentProvider() {
if (mIContentProvider == null) {
hookIContentProviderAsNeeded();
}
return mIContentProvider;
}
public ComponentsHandler getComponentsHandler() {
return mComponentsHandler;
}
public ResolveInfo resolveActivity(Intent intent) {
return this.resolveActivity(intent, 0);
}
public ResolveInfo resolveActivity(Intent intent, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ResolveInfo resolveInfo = plugin.resolveActivity(intent, flags);
if (null != resolveInfo) {
return resolveInfo;
}
}
return null;
}
public ResolveInfo resolveService(Intent intent, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ResolveInfo resolveInfo = plugin.resolveService(intent, flags);
if (null != resolveInfo) {
return resolveInfo;
}
}
return null;
}
public ProviderInfo resolveContentProvider(String name, int flags) {
for (LoadedPlugin plugin : this.mPlugins.values()) {
ProviderInfo providerInfo = plugin.resolveContentProvider(name, flags);
if (null != providerInfo) {
return providerInfo;
}
}
return null;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryIntentActivities(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryIntentServices(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
/**
* used in PluginPackageManager, do not invoke it from outside.
*/
@Deprecated
public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();
for (LoadedPlugin plugin : this.mPlugins.values()) {
List<ResolveInfo> result = plugin.queryBroadcastReceivers(intent, flags);
if (null != result && result.size() > 0) {
resolveInfos.addAll(result);
}
}
return resolveInfos;
}
public interface Callback {
void onAddedLoadedPlugin(LoadedPlugin plugin);
}
} |
209655_31 | // Copyright 2021-present StarRocks, Inc. 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
//
// 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 com.starrocks.qe.scheduler.dag;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starrocks.planner.DataPartition;
import com.starrocks.planner.DataSink;
import com.starrocks.planner.DataStreamSink;
import com.starrocks.planner.MultiCastDataSink;
import com.starrocks.planner.MultiCastPlanFragment;
import com.starrocks.planner.PlanFragment;
import com.starrocks.planner.PlanFragmentId;
import com.starrocks.planner.ScanNode;
import com.starrocks.qe.QueryStatisticsItem;
import com.starrocks.qe.scheduler.NonRecoverableException;
import com.starrocks.qe.scheduler.SchedulerException;
import com.starrocks.sql.common.ErrorType;
import com.starrocks.sql.common.StarRocksPlannerException;
import com.starrocks.system.ComputeNode;
import com.starrocks.thrift.TNetworkAddress;
import com.starrocks.thrift.TPlanFragmentDestination;
import com.starrocks.thrift.TUniqueId;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The execution DAG represents the distributed execution of a job, mainly including parallel instances of fragments and the
* communication between them.
*
* <p>The execution DAG consists of the following components:
*
* <ul>
* <li>The {@link ExecutionFragment} represents a collection of multiple parallel instances of a {@link PlanFragment}.
* <li>The {@link FragmentInstance} represents a parallel instance of a {@link PlanFragment}.
* <li> The {@link FragmentInstanceExecState} represents the execution state of a {@link FragmentInstance} for a single attempt.
* </ul>
*/
public class ExecutionDAG {
private static final Logger LOG = LogManager.getLogger(ExecutionDAG.class);
private final JobSpec jobSpec;
private final List<ExecutionFragment> fragments;
private final Map<PlanFragmentId, ExecutionFragment> idToFragment;
/**
* {@code instanceIdToInstance} and {@link #workerIdToNumInstances} will be calculated in {@link #finalizeDAG()},
* after all the fragment instances have already been added to the DAG .
*/
private final Map<TUniqueId, FragmentInstance> instanceIdToInstance;
private Map<Long, Integer> workerIdToNumInstances = Maps.newHashMap();
/**
* The executions will be added to {@code indexInJobToExecState}, when it is deploying.
*/
private final ConcurrentMap<Integer, FragmentInstanceExecState> indexInJobToExecState = new ConcurrentSkipListMap<>();
/**
* Backend which state need to be checked when joining this coordinator.
* It is supposed to be the subset of backendExecStates.
*/
private final List<FragmentInstanceExecState> needCheckExecutions = Lists.newArrayList();
/**
* Used only by channel stream load, records the mapping from channel id to target BE's address
*/
private final Map<Integer, TNetworkAddress> channelIdToBEHTTP = Maps.newHashMap();
private final Map<Integer, TNetworkAddress> channelIdToBEPort = Maps.newHashMap();
private ExecutionDAG(JobSpec jobSpec) {
this.jobSpec = jobSpec;
this.fragments = Lists.newArrayList();
this.idToFragment = Maps.newHashMap();
this.instanceIdToInstance = Maps.newHashMap();
}
public static ExecutionDAG build(JobSpec jobSpec) {
ExecutionDAG executionDAG = new ExecutionDAG(jobSpec);
executionDAG.attachFragments(jobSpec.getFragments());
return executionDAG;
}
public void attachFragments(List<PlanFragment> planFragments) {
for (PlanFragment planFragment : planFragments) {
ExecutionFragment fragment = new ExecutionFragment(this, planFragment, fragments.size());
fragments.add(fragment);
idToFragment.put(planFragment.getFragmentId(), fragment);
}
}
public Set<TUniqueId> getInstanceIds() {
return instanceIdToInstance.keySet();
}
public Collection<FragmentInstance> getInstances() {
return instanceIdToInstance.values();
}
public FragmentInstance getInstanceByInstanceId(TUniqueId instanceId) {
return instanceIdToInstance.get(instanceId);
}
public ExecutionFragment getRootFragment() {
return fragments.get(0);
}
public Collection<ScanNode> getScanNodes() {
return fragments.stream()
.flatMap(fragment -> fragment.getScanNodes().stream())
.collect(Collectors.toList());
}
public List<ExecutionFragment> getFragmentsInCreatedOrder() {
return fragments;
}
public List<ExecutionFragment> getFragmentsInPreorder() {
return fragments;
}
public List<ExecutionFragment> getFragmentsInPostorder() {
return Lists.reverse(fragments);
}
/**
* Compute the topological order of the fragment tree.
* It will divide fragments to several groups.
* - There is no data dependency among fragments in a group.
* - All the upstream fragments of the fragments in a group must belong to the previous groups.
* - Each group should be delivered sequentially, and fragments in a group can be delivered concurrently.
*
* <p>For example, the following tree will produce four groups: [[1], [2, 3, 4], [5, 6], [7]]
* <pre>{@code
* 1
* │
* ┌────┼────┐
* │ │ │
* 2 3 4
* │ │ │
* ┌──┴─┐ │ │
* │ │ │ │
* 5 6 │ │
* │ │ │
* └──┼────┘
* │
* 7
* }</pre>
*
* @return multiple fragment groups.
*/
public List<List<ExecutionFragment>> getFragmentsInTopologicalOrderFromRoot() {
Queue<ExecutionFragment> queue = Lists.newLinkedList();
Map<ExecutionFragment, Integer> inDegrees = Maps.newHashMap();
ExecutionFragment root = getRootFragment();
// Compute in-degree of each fragment by BFS.
// `queue` contains the fragments need to visit its in-edges.
inDegrees.put(root, 0);
queue.add(root);
while (!queue.isEmpty()) {
ExecutionFragment fragment = queue.poll();
for (int i = 0; i < fragment.childrenSize(); i++) {
ExecutionFragment child = fragment.getChild(i);
Integer v = inDegrees.get(child);
if (v != null) {
// Has added this child to queue before, don't add again.
inDegrees.put(child, v + 1);
} else {
inDegrees.put(child, 1);
queue.add(child);
}
}
}
if (fragments.size() != inDegrees.size()) {
for (ExecutionFragment fragment : fragments) {
if (!inDegrees.containsKey(fragment)) {
LOG.warn("This fragment does not belong to the fragment tree: {}", fragment.getFragmentId());
}
}
throw new StarRocksPlannerException("Some fragments do not belong to the fragment tree",
ErrorType.INTERNAL_ERROR);
}
// Compute fragment groups by BFS.
// `queue` contains the fragments whose in-degree is zero.
queue.add(root);
List<List<ExecutionFragment>> groups = Lists.newArrayList();
int numOutputFragments = 0;
while (!queue.isEmpty()) {
int groupSize = queue.size();
List<ExecutionFragment> group = new ArrayList<>(groupSize);
// The next `groupSize` fragments can be delivered concurrently, because zero in-degree indicates that
// they don't depend on each other and all the fragments depending on them have been delivered.
for (int i = 0; i < groupSize; ++i) {
ExecutionFragment fragment = Preconditions.checkNotNull(queue.poll());
group.add(fragment);
for (int j = 0; j < fragment.childrenSize(); j++) {
ExecutionFragment child = fragment.getChild(j);
int degree = inDegrees.compute(child, (k, v) -> Preconditions.checkNotNull(v) - 1);
if (degree == 0) {
queue.add(child);
}
}
}
groups.add(group);
numOutputFragments += groupSize;
}
if (fragments.size() != numOutputFragments) {
throw new StarRocksPlannerException("There are some circles in the fragment tree",
ErrorType.INTERNAL_ERROR);
}
return groups;
}
public Map<PlanFragmentId, ExecutionFragment> getIdToFragment() {
return idToFragment;
}
public ExecutionFragment getFragment(PlanFragmentId fragmentId) {
return idToFragment.get(fragmentId);
}
public boolean isGatherOutput() {
return fragments.get(0).getPlanFragment().getDataPartition() == DataPartition.UNPARTITIONED;
}
/**
* Do the finalize work after all the fragment instances have already been added to the DAG, including:
*
* <ul>
* <li>Assign instance id to fragment instances.
* <li>Assign monotonic unique indexInJob to fragment instances to keep consistent order with indexInFragment.
* Also see {@link FragmentInstance#getIndexInJob()}.
* <li>Connect each fragment to its destination fragments
* <li>Setup {@link #workerIdToNumInstances}, {@link #channelIdToBEHTTP}, and {@link #channelIdToBEPort}
* </ul>
*
* @throws SchedulerException when there is something wrong for the plan or execution information.
*/
public void finalizeDAG() throws SchedulerException {
// Assign monotonic unique indexInJob to fragment instances to keep consistent order with indexInFragment.
int index = 0;
for (ExecutionFragment fragment : fragments) {
for (FragmentInstance instance : fragment.getInstances()) {
setInstanceId(instance);
instance.setIndexInJob(index++);
}
}
for (ExecutionFragment fragment : fragments) {
connectFragmentToDestFragments(fragment);
}
workerIdToNumInstances = fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.collect(Collectors.groupingBy(
FragmentInstance::getWorkerId,
Collectors.summingInt(instance -> 1)
));
if (jobSpec.isStreamLoad()) {
fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.forEach(instance -> Stream.concat(
instance.getNode2ScanRanges().values().stream(),
instance.getNode2DriverSeqToScanRanges().values().stream()
.flatMap(driverSeqToScanRanges -> driverSeqToScanRanges.values().stream()))
.flatMap(Collection::stream)
.forEach(scanRange -> {
int channelId = scanRange.scan_range.broker_scan_range.channel_id;
ComputeNode worker = instance.getWorker();
channelIdToBEHTTP.put(channelId, worker.getHttpAddress());
channelIdToBEPort.put(channelId, worker.getAddress());
})
);
}
}
public Map<Integer, TNetworkAddress> getChannelIdToBEHTTP() {
return channelIdToBEHTTP;
}
public Map<Integer, TNetworkAddress> getChannelIdToBEPort() {
return channelIdToBEPort;
}
public int getNumInstancesOfWorkerId(Long addr) {
return workerIdToNumInstances.get(addr);
}
public void addExecution(FragmentInstanceExecState execution) {
FragmentInstance instance = instanceIdToInstance.get(execution.getInstanceId());
if (instance != null) {
instance.setExecution(execution);
}
indexInJobToExecState.put(execution.getIndexInJob(), execution);
}
public void addNeedCheckExecution(FragmentInstanceExecState execution) {
needCheckExecutions.add(execution);
}
public List<FragmentInstanceExecState> getNeedCheckExecutions() {
return needCheckExecutions;
}
public Collection<Integer> getExecutionIndexesInJob() {
return indexInJobToExecState.keySet();
}
public Collection<FragmentInstanceExecState> getExecutions() {
return indexInJobToExecState.values();
}
public FragmentInstanceExecState getExecution(int indexInJob) {
return indexInJobToExecState.get(indexInJob);
}
public List<QueryStatisticsItem.FragmentInstanceInfo> getFragmentInstanceInfos() {
return fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.map(FragmentInstance::getExecution)
.filter(Objects::nonNull)
.map(FragmentInstanceExecState::buildFragmentInstanceInfo)
.collect(Collectors.toList());
}
public void resetExecutions() {
fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.forEach(instance -> instance.setExecution(null));
indexInJobToExecState.clear();
needCheckExecutions.clear();
instanceIdToInstance.clear();
}
/**
* Compute destinations and # senders per exchange node.
*
* @param execFragment The fragment to be initialized.
* @throws SchedulerException when there is something wrong for the plan or execution information.
*/
private void connectFragmentToDestFragments(ExecutionFragment execFragment) throws SchedulerException {
if (execFragment.getPlanFragment() instanceof MultiCastPlanFragment) {
connectMultiCastFragmentToDestFragments(execFragment, (MultiCastPlanFragment) execFragment.getPlanFragment());
} else {
connectNormalFragmentToDestFragments(execFragment);
}
}
private boolean needScheduleByLocalBucketShuffleJoin(ExecutionFragment destFragment, DataSink sourceSink) {
if (destFragment.isLocalBucketShuffleJoin() && sourceSink instanceof DataStreamSink) {
DataStreamSink streamSink = (DataStreamSink) sourceSink;
return streamSink.getOutputPartition().isBucketShuffle();
}
return false;
}
private void connectMultiCastFragmentToDestFragments(ExecutionFragment execFragment, MultiCastPlanFragment fragment)
throws SchedulerException {
Preconditions.checkState(fragment.getSink() instanceof MultiCastDataSink);
MultiCastDataSink multiSink = (MultiCastDataSink) fragment.getSink();
// set # of senders
for (int i = 0; i < fragment.getDestFragmentList().size(); i++) {
PlanFragment destFragment = fragment.getDestFragmentList().get(i);
if (destFragment == null) {
continue;
}
ExecutionFragment destExecFragment = idToFragment.get(destFragment.getFragmentId());
DataStreamSink sink = multiSink.getDataStreamSinks().get(i);
// Set params for pipeline level shuffle.
fragment.getDestNode(i).setPartitionType(fragment.getOutputPartition().getType());
sink.setExchDop(destFragment.getPipelineDop());
Integer exchangeId = sink.getExchNodeId().asInt();
// MultiCastSink only send to itself, destination exchange only one sender,
// and it doesn't support sort-merge
Preconditions.checkState(!destExecFragment.getNumSendersPerExchange().containsKey(exchangeId));
destExecFragment.getNumSendersPerExchange().put(exchangeId, 1);
if (needScheduleByLocalBucketShuffleJoin(destExecFragment, sink)) {
throw new NonRecoverableException("CTE consumer fragment cannot be bucket shuffle join");
} else {
// add destination host to this fragment's destination
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
multiSink.getDestinations().get(i).add(dest);
}
}
}
}
private void connectNormalFragmentToDestFragments(ExecutionFragment execFragment) {
PlanFragment fragment = execFragment.getPlanFragment();
PlanFragment destFragment = fragment.getDestFragment();
if (destFragment == null) {
// root plan fragment
return;
}
ExecutionFragment destExecFragment = idToFragment.get(destFragment.getFragmentId());
DataSink sink = fragment.getSink();
// Set params for pipeline level shuffle.
fragment.getDestNode().setPartitionType(fragment.getOutputPartition().getType());
int destDop = destFragment.getPipelineDop();
if (sink instanceof DataStreamSink) {
DataStreamSink dataStreamSink = (DataStreamSink) sink;
dataStreamSink.setExchDop(destFragment.getPipelineDop());
}
Integer exchangeId = sink.getExchNodeId().asInt();
destExecFragment.getNumSendersPerExchange().compute(exchangeId, (k, oldNumSenders) -> {
if (oldNumSenders == null) {
return execFragment.getInstances().size();
}
// we might have multiple fragments sending to this exchange node
// (distributed MERGE), which is why we need to add up the #senders
// e.g. sort-merge
return oldNumSenders + execFragment.getInstances().size();
});
// We can only handle unpartitioned (= broadcast) and hash-partitioned output at the moment.
if (needScheduleByLocalBucketShuffleJoin(destExecFragment, sink)) {
Map<Integer, FragmentInstance> bucketSeqToDestInstance = Maps.newHashMap();
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
for (int bucketSeq : destInstance.getBucketSeqs()) {
bucketSeqToDestInstance.put(bucketSeq, destInstance);
}
}
TNetworkAddress dummyServer = new TNetworkAddress("0.0.0.0", 0);
int bucketNum = destExecFragment.getBucketNum();
for (int bucketSeq = 0; bucketSeq < bucketNum; bucketSeq++) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
FragmentInstance destInstance = bucketSeqToDestInstance.get(bucketSeq);
if (destInstance == null) {
// dest bucket may be pruned, these bucket dest should be set an invalid value
// and will be deal with in BE's DataStreamSender
dest.setFragment_instance_id(new TUniqueId(-1, -1));
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(dummyServer);
dest.setBrpc_server(dummyServer);
} else {
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
int driverSeq = destInstance.getDriverSeqOfBucketSeq(bucketSeq);
if (driverSeq != FragmentInstance.ABSENT_DRIVER_SEQUENCE) {
dest.setPipeline_driver_sequence(driverSeq % destDop);
}
}
execFragment.addDestination(dest);
}
} else {
// add destination host to this fragment's destination
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
execFragment.addDestination(dest);
}
}
}
private void setInstanceId(FragmentInstance instance) {
TUniqueId jobId = jobSpec.getQueryId();
TUniqueId instanceId = new TUniqueId();
instanceId.setHi(jobId.hi);
instanceId.setLo(jobId.lo + instanceIdToInstance.size() + 1);
instance.setInstanceId(instanceId);
instanceIdToInstance.put(instanceId, instance);
}
}
| StarRocks/starrocks | fe/fe-core/src/main/java/com/starrocks/qe/scheduler/dag/ExecutionDAG.java | 5,245 | // root plan fragment | line_comment | nl | // Copyright 2021-present StarRocks, Inc. 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
//
// 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 com.starrocks.qe.scheduler.dag;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starrocks.planner.DataPartition;
import com.starrocks.planner.DataSink;
import com.starrocks.planner.DataStreamSink;
import com.starrocks.planner.MultiCastDataSink;
import com.starrocks.planner.MultiCastPlanFragment;
import com.starrocks.planner.PlanFragment;
import com.starrocks.planner.PlanFragmentId;
import com.starrocks.planner.ScanNode;
import com.starrocks.qe.QueryStatisticsItem;
import com.starrocks.qe.scheduler.NonRecoverableException;
import com.starrocks.qe.scheduler.SchedulerException;
import com.starrocks.sql.common.ErrorType;
import com.starrocks.sql.common.StarRocksPlannerException;
import com.starrocks.system.ComputeNode;
import com.starrocks.thrift.TNetworkAddress;
import com.starrocks.thrift.TPlanFragmentDestination;
import com.starrocks.thrift.TUniqueId;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The execution DAG represents the distributed execution of a job, mainly including parallel instances of fragments and the
* communication between them.
*
* <p>The execution DAG consists of the following components:
*
* <ul>
* <li>The {@link ExecutionFragment} represents a collection of multiple parallel instances of a {@link PlanFragment}.
* <li>The {@link FragmentInstance} represents a parallel instance of a {@link PlanFragment}.
* <li> The {@link FragmentInstanceExecState} represents the execution state of a {@link FragmentInstance} for a single attempt.
* </ul>
*/
public class ExecutionDAG {
private static final Logger LOG = LogManager.getLogger(ExecutionDAG.class);
private final JobSpec jobSpec;
private final List<ExecutionFragment> fragments;
private final Map<PlanFragmentId, ExecutionFragment> idToFragment;
/**
* {@code instanceIdToInstance} and {@link #workerIdToNumInstances} will be calculated in {@link #finalizeDAG()},
* after all the fragment instances have already been added to the DAG .
*/
private final Map<TUniqueId, FragmentInstance> instanceIdToInstance;
private Map<Long, Integer> workerIdToNumInstances = Maps.newHashMap();
/**
* The executions will be added to {@code indexInJobToExecState}, when it is deploying.
*/
private final ConcurrentMap<Integer, FragmentInstanceExecState> indexInJobToExecState = new ConcurrentSkipListMap<>();
/**
* Backend which state need to be checked when joining this coordinator.
* It is supposed to be the subset of backendExecStates.
*/
private final List<FragmentInstanceExecState> needCheckExecutions = Lists.newArrayList();
/**
* Used only by channel stream load, records the mapping from channel id to target BE's address
*/
private final Map<Integer, TNetworkAddress> channelIdToBEHTTP = Maps.newHashMap();
private final Map<Integer, TNetworkAddress> channelIdToBEPort = Maps.newHashMap();
private ExecutionDAG(JobSpec jobSpec) {
this.jobSpec = jobSpec;
this.fragments = Lists.newArrayList();
this.idToFragment = Maps.newHashMap();
this.instanceIdToInstance = Maps.newHashMap();
}
public static ExecutionDAG build(JobSpec jobSpec) {
ExecutionDAG executionDAG = new ExecutionDAG(jobSpec);
executionDAG.attachFragments(jobSpec.getFragments());
return executionDAG;
}
public void attachFragments(List<PlanFragment> planFragments) {
for (PlanFragment planFragment : planFragments) {
ExecutionFragment fragment = new ExecutionFragment(this, planFragment, fragments.size());
fragments.add(fragment);
idToFragment.put(planFragment.getFragmentId(), fragment);
}
}
public Set<TUniqueId> getInstanceIds() {
return instanceIdToInstance.keySet();
}
public Collection<FragmentInstance> getInstances() {
return instanceIdToInstance.values();
}
public FragmentInstance getInstanceByInstanceId(TUniqueId instanceId) {
return instanceIdToInstance.get(instanceId);
}
public ExecutionFragment getRootFragment() {
return fragments.get(0);
}
public Collection<ScanNode> getScanNodes() {
return fragments.stream()
.flatMap(fragment -> fragment.getScanNodes().stream())
.collect(Collectors.toList());
}
public List<ExecutionFragment> getFragmentsInCreatedOrder() {
return fragments;
}
public List<ExecutionFragment> getFragmentsInPreorder() {
return fragments;
}
public List<ExecutionFragment> getFragmentsInPostorder() {
return Lists.reverse(fragments);
}
/**
* Compute the topological order of the fragment tree.
* It will divide fragments to several groups.
* - There is no data dependency among fragments in a group.
* - All the upstream fragments of the fragments in a group must belong to the previous groups.
* - Each group should be delivered sequentially, and fragments in a group can be delivered concurrently.
*
* <p>For example, the following tree will produce four groups: [[1], [2, 3, 4], [5, 6], [7]]
* <pre>{@code
* 1
* │
* ┌────┼────┐
* │ │ │
* 2 3 4
* │ │ │
* ┌──┴─┐ │ │
* │ │ │ │
* 5 6 │ │
* │ │ │
* └──┼────┘
* │
* 7
* }</pre>
*
* @return multiple fragment groups.
*/
public List<List<ExecutionFragment>> getFragmentsInTopologicalOrderFromRoot() {
Queue<ExecutionFragment> queue = Lists.newLinkedList();
Map<ExecutionFragment, Integer> inDegrees = Maps.newHashMap();
ExecutionFragment root = getRootFragment();
// Compute in-degree of each fragment by BFS.
// `queue` contains the fragments need to visit its in-edges.
inDegrees.put(root, 0);
queue.add(root);
while (!queue.isEmpty()) {
ExecutionFragment fragment = queue.poll();
for (int i = 0; i < fragment.childrenSize(); i++) {
ExecutionFragment child = fragment.getChild(i);
Integer v = inDegrees.get(child);
if (v != null) {
// Has added this child to queue before, don't add again.
inDegrees.put(child, v + 1);
} else {
inDegrees.put(child, 1);
queue.add(child);
}
}
}
if (fragments.size() != inDegrees.size()) {
for (ExecutionFragment fragment : fragments) {
if (!inDegrees.containsKey(fragment)) {
LOG.warn("This fragment does not belong to the fragment tree: {}", fragment.getFragmentId());
}
}
throw new StarRocksPlannerException("Some fragments do not belong to the fragment tree",
ErrorType.INTERNAL_ERROR);
}
// Compute fragment groups by BFS.
// `queue` contains the fragments whose in-degree is zero.
queue.add(root);
List<List<ExecutionFragment>> groups = Lists.newArrayList();
int numOutputFragments = 0;
while (!queue.isEmpty()) {
int groupSize = queue.size();
List<ExecutionFragment> group = new ArrayList<>(groupSize);
// The next `groupSize` fragments can be delivered concurrently, because zero in-degree indicates that
// they don't depend on each other and all the fragments depending on them have been delivered.
for (int i = 0; i < groupSize; ++i) {
ExecutionFragment fragment = Preconditions.checkNotNull(queue.poll());
group.add(fragment);
for (int j = 0; j < fragment.childrenSize(); j++) {
ExecutionFragment child = fragment.getChild(j);
int degree = inDegrees.compute(child, (k, v) -> Preconditions.checkNotNull(v) - 1);
if (degree == 0) {
queue.add(child);
}
}
}
groups.add(group);
numOutputFragments += groupSize;
}
if (fragments.size() != numOutputFragments) {
throw new StarRocksPlannerException("There are some circles in the fragment tree",
ErrorType.INTERNAL_ERROR);
}
return groups;
}
public Map<PlanFragmentId, ExecutionFragment> getIdToFragment() {
return idToFragment;
}
public ExecutionFragment getFragment(PlanFragmentId fragmentId) {
return idToFragment.get(fragmentId);
}
public boolean isGatherOutput() {
return fragments.get(0).getPlanFragment().getDataPartition() == DataPartition.UNPARTITIONED;
}
/**
* Do the finalize work after all the fragment instances have already been added to the DAG, including:
*
* <ul>
* <li>Assign instance id to fragment instances.
* <li>Assign monotonic unique indexInJob to fragment instances to keep consistent order with indexInFragment.
* Also see {@link FragmentInstance#getIndexInJob()}.
* <li>Connect each fragment to its destination fragments
* <li>Setup {@link #workerIdToNumInstances}, {@link #channelIdToBEHTTP}, and {@link #channelIdToBEPort}
* </ul>
*
* @throws SchedulerException when there is something wrong for the plan or execution information.
*/
public void finalizeDAG() throws SchedulerException {
// Assign monotonic unique indexInJob to fragment instances to keep consistent order with indexInFragment.
int index = 0;
for (ExecutionFragment fragment : fragments) {
for (FragmentInstance instance : fragment.getInstances()) {
setInstanceId(instance);
instance.setIndexInJob(index++);
}
}
for (ExecutionFragment fragment : fragments) {
connectFragmentToDestFragments(fragment);
}
workerIdToNumInstances = fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.collect(Collectors.groupingBy(
FragmentInstance::getWorkerId,
Collectors.summingInt(instance -> 1)
));
if (jobSpec.isStreamLoad()) {
fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.forEach(instance -> Stream.concat(
instance.getNode2ScanRanges().values().stream(),
instance.getNode2DriverSeqToScanRanges().values().stream()
.flatMap(driverSeqToScanRanges -> driverSeqToScanRanges.values().stream()))
.flatMap(Collection::stream)
.forEach(scanRange -> {
int channelId = scanRange.scan_range.broker_scan_range.channel_id;
ComputeNode worker = instance.getWorker();
channelIdToBEHTTP.put(channelId, worker.getHttpAddress());
channelIdToBEPort.put(channelId, worker.getAddress());
})
);
}
}
public Map<Integer, TNetworkAddress> getChannelIdToBEHTTP() {
return channelIdToBEHTTP;
}
public Map<Integer, TNetworkAddress> getChannelIdToBEPort() {
return channelIdToBEPort;
}
public int getNumInstancesOfWorkerId(Long addr) {
return workerIdToNumInstances.get(addr);
}
public void addExecution(FragmentInstanceExecState execution) {
FragmentInstance instance = instanceIdToInstance.get(execution.getInstanceId());
if (instance != null) {
instance.setExecution(execution);
}
indexInJobToExecState.put(execution.getIndexInJob(), execution);
}
public void addNeedCheckExecution(FragmentInstanceExecState execution) {
needCheckExecutions.add(execution);
}
public List<FragmentInstanceExecState> getNeedCheckExecutions() {
return needCheckExecutions;
}
public Collection<Integer> getExecutionIndexesInJob() {
return indexInJobToExecState.keySet();
}
public Collection<FragmentInstanceExecState> getExecutions() {
return indexInJobToExecState.values();
}
public FragmentInstanceExecState getExecution(int indexInJob) {
return indexInJobToExecState.get(indexInJob);
}
public List<QueryStatisticsItem.FragmentInstanceInfo> getFragmentInstanceInfos() {
return fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.map(FragmentInstance::getExecution)
.filter(Objects::nonNull)
.map(FragmentInstanceExecState::buildFragmentInstanceInfo)
.collect(Collectors.toList());
}
public void resetExecutions() {
fragments.stream()
.flatMap(fragment -> fragment.getInstances().stream())
.forEach(instance -> instance.setExecution(null));
indexInJobToExecState.clear();
needCheckExecutions.clear();
instanceIdToInstance.clear();
}
/**
* Compute destinations and # senders per exchange node.
*
* @param execFragment The fragment to be initialized.
* @throws SchedulerException when there is something wrong for the plan or execution information.
*/
private void connectFragmentToDestFragments(ExecutionFragment execFragment) throws SchedulerException {
if (execFragment.getPlanFragment() instanceof MultiCastPlanFragment) {
connectMultiCastFragmentToDestFragments(execFragment, (MultiCastPlanFragment) execFragment.getPlanFragment());
} else {
connectNormalFragmentToDestFragments(execFragment);
}
}
private boolean needScheduleByLocalBucketShuffleJoin(ExecutionFragment destFragment, DataSink sourceSink) {
if (destFragment.isLocalBucketShuffleJoin() && sourceSink instanceof DataStreamSink) {
DataStreamSink streamSink = (DataStreamSink) sourceSink;
return streamSink.getOutputPartition().isBucketShuffle();
}
return false;
}
private void connectMultiCastFragmentToDestFragments(ExecutionFragment execFragment, MultiCastPlanFragment fragment)
throws SchedulerException {
Preconditions.checkState(fragment.getSink() instanceof MultiCastDataSink);
MultiCastDataSink multiSink = (MultiCastDataSink) fragment.getSink();
// set # of senders
for (int i = 0; i < fragment.getDestFragmentList().size(); i++) {
PlanFragment destFragment = fragment.getDestFragmentList().get(i);
if (destFragment == null) {
continue;
}
ExecutionFragment destExecFragment = idToFragment.get(destFragment.getFragmentId());
DataStreamSink sink = multiSink.getDataStreamSinks().get(i);
// Set params for pipeline level shuffle.
fragment.getDestNode(i).setPartitionType(fragment.getOutputPartition().getType());
sink.setExchDop(destFragment.getPipelineDop());
Integer exchangeId = sink.getExchNodeId().asInt();
// MultiCastSink only send to itself, destination exchange only one sender,
// and it doesn't support sort-merge
Preconditions.checkState(!destExecFragment.getNumSendersPerExchange().containsKey(exchangeId));
destExecFragment.getNumSendersPerExchange().put(exchangeId, 1);
if (needScheduleByLocalBucketShuffleJoin(destExecFragment, sink)) {
throw new NonRecoverableException("CTE consumer fragment cannot be bucket shuffle join");
} else {
// add destination host to this fragment's destination
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
multiSink.getDestinations().get(i).add(dest);
}
}
}
}
private void connectNormalFragmentToDestFragments(ExecutionFragment execFragment) {
PlanFragment fragment = execFragment.getPlanFragment();
PlanFragment destFragment = fragment.getDestFragment();
if (destFragment == null) {
// root plan<SUF>
return;
}
ExecutionFragment destExecFragment = idToFragment.get(destFragment.getFragmentId());
DataSink sink = fragment.getSink();
// Set params for pipeline level shuffle.
fragment.getDestNode().setPartitionType(fragment.getOutputPartition().getType());
int destDop = destFragment.getPipelineDop();
if (sink instanceof DataStreamSink) {
DataStreamSink dataStreamSink = (DataStreamSink) sink;
dataStreamSink.setExchDop(destFragment.getPipelineDop());
}
Integer exchangeId = sink.getExchNodeId().asInt();
destExecFragment.getNumSendersPerExchange().compute(exchangeId, (k, oldNumSenders) -> {
if (oldNumSenders == null) {
return execFragment.getInstances().size();
}
// we might have multiple fragments sending to this exchange node
// (distributed MERGE), which is why we need to add up the #senders
// e.g. sort-merge
return oldNumSenders + execFragment.getInstances().size();
});
// We can only handle unpartitioned (= broadcast) and hash-partitioned output at the moment.
if (needScheduleByLocalBucketShuffleJoin(destExecFragment, sink)) {
Map<Integer, FragmentInstance> bucketSeqToDestInstance = Maps.newHashMap();
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
for (int bucketSeq : destInstance.getBucketSeqs()) {
bucketSeqToDestInstance.put(bucketSeq, destInstance);
}
}
TNetworkAddress dummyServer = new TNetworkAddress("0.0.0.0", 0);
int bucketNum = destExecFragment.getBucketNum();
for (int bucketSeq = 0; bucketSeq < bucketNum; bucketSeq++) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
FragmentInstance destInstance = bucketSeqToDestInstance.get(bucketSeq);
if (destInstance == null) {
// dest bucket may be pruned, these bucket dest should be set an invalid value
// and will be deal with in BE's DataStreamSender
dest.setFragment_instance_id(new TUniqueId(-1, -1));
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(dummyServer);
dest.setBrpc_server(dummyServer);
} else {
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
int driverSeq = destInstance.getDriverSeqOfBucketSeq(bucketSeq);
if (driverSeq != FragmentInstance.ABSENT_DRIVER_SEQUENCE) {
dest.setPipeline_driver_sequence(driverSeq % destDop);
}
}
execFragment.addDestination(dest);
}
} else {
// add destination host to this fragment's destination
for (FragmentInstance destInstance : destExecFragment.getInstances()) {
TPlanFragmentDestination dest = new TPlanFragmentDestination();
dest.setFragment_instance_id(destInstance.getInstanceId());
ComputeNode worker = destInstance.getWorker();
// NOTE(zc): can be removed in version 4.0
dest.setDeprecated_server(worker.getAddress());
dest.setBrpc_server(worker.getBrpcIpAddress());
execFragment.addDestination(dest);
}
}
}
private void setInstanceId(FragmentInstance instance) {
TUniqueId jobId = jobSpec.getQueryId();
TUniqueId instanceId = new TUniqueId();
instanceId.setHi(jobId.hi);
instanceId.setLo(jobId.lo + instanceIdToInstance.size() + 1);
instance.setInstanceId(instanceId);
instanceIdToInstance.put(instanceId, instance);
}
}
|
209696_9 | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest: lijsten maken met derby vulling After
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable vullen met de lege shows en movies.
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in tweede unittest
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
| Cerios/cerioscoop-web | src/test/java/nl/cerios/cerioscoop/service/GeneralServiceTest.java | 2,880 | //Tweede unittest: lijsten maken met derby vulling After | line_comment | nl | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest:<SUF>
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable vullen met de lege shows en movies.
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in tweede unittest
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
|
209696_10 | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest: lijsten maken met derby vulling After
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable vullen met de lege shows en movies.
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in tweede unittest
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
| Cerios/cerioscoop-web | src/test/java/nl/cerios/cerioscoop/service/GeneralServiceTest.java | 2,880 | //de todaysShowsTable vullen met de lege shows en movies. | line_comment | nl | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest: lijsten maken met derby vulling After
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable<SUF>
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in tweede unittest
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
|
209696_11 | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest: lijsten maken met derby vulling After
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable vullen met de lege shows en movies.
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in tweede unittest
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
| Cerios/cerioscoop-web | src/test/java/nl/cerios/cerioscoop/service/GeneralServiceTest.java | 2,880 | //voorstellingen in tweede unittest | line_comment | nl | package nl.cerios.cerioscoop.service;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.util.DateUtils;
import nl.cerios.testutil.DatabaseTest;
public class GeneralServiceTest extends DatabaseTest {
@InjectMocks
private GeneralService generalService;
private final DateUtils dateUtils = new DateUtils();
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetMovies() {
final List<Movie> movies = generalService.getMovies();
Assert.assertNotNull(movies);
Assert.assertEquals(7, movies.size());
}
@Test
public void testGetShows() {
final List<Show> shows = generalService.getShows();
Assert.assertNotNull(shows);
Assert.assertEquals(7, shows.size());
}
@Test
public void testGetCustomers() {
final List<Customer> customers = generalService.getCustomers();
Assert.assertNotNull(customers);
Assert.assertEquals(3, customers.size());
}
@Test
public void testGetFirstShowforToday() throws ParseException{
//Shows
final Show showOne = new Show(0, 1,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-20-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showTwo = new Show(0, 2,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("07-23-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
final Show showThree = new Show(0, 3,
dateUtils.convertUtilDateToSqlDate(dateUtils.toDate(dateUtils.toDateFormat("09-03-2020"))),
dateUtils.convertUtilDateToSqlTime(dateUtils.toTime(dateUtils.toTimeFormat("20:00:00"))));
//Putting all movies in a list
final List<Show> listOfShows = new ArrayList<>();
listOfShows.add(0, showOne);
listOfShows.add(1, showTwo);
listOfShows.add(2, showThree);
//First show after the current date control
Assert.assertEquals(showOne.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showTwo.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
Assert.assertNotEquals(showThree.getShowDate() ,generalService.getFirstShowforToday(listOfShows).getShowDate());
}
@Test
public void testGetMovieByMovieId() throws MovieNotFoundException{
//Movies
final Movie movieOne = new MovieBuilder()
.withMovieId(BigInteger.valueOf(1))
.withMovieTitle("top titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieTwo = new MovieBuilder()
.withMovieId(BigInteger.valueOf(2))
.withMovieTitle("lekkere titel")
.withMovieDescription("bagger v-film")
.build();
final Movie movieThree = new MovieBuilder()
.withMovieId(BigInteger.valueOf(3))
.withMovieTitle("keke titel")
.withMovieDescription("bagger v-film")
.build();
//Putting all movies in a list
final List<Movie> listOfMovies = new ArrayList<>();
listOfMovies.add(0, movieOne);
listOfMovies.add(1, movieTwo);
listOfMovies.add(2, movieThree);
//Movie control
Assert.assertEquals(movieOne ,generalService.getMovieByMovieId(movieOne.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieTwo ,generalService.getMovieByMovieId(movieTwo.getMovieId().intValue(), listOfMovies));
Assert.assertEquals(movieThree ,generalService.getMovieByMovieId(movieThree.getMovieId().intValue(), listOfMovies));
}
@Test
public void testRegisterCustomer() throws ParseException {
final int idOfCustomerToBeRegistered = 4;
final Customer customerOne = new Customer(idOfCustomerToBeRegistered, "Michael", "Boogerd", "MB", "MB123", "[email protected]");
final Customer customerBefore = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNull(customerBefore);
generalService.registerCustomer(customerOne);
final Customer customerAfter = getCustomer(idOfCustomerToBeRegistered);
Assert.assertNotNull(customerAfter);
Assert.assertEquals(customerOne.getFirstName(), customerAfter.getFirstName());
Assert.assertEquals(customerOne.getLastName(), customerAfter.getLastName());
Assert.assertEquals(customerOne.getUsername(), customerAfter.getUsername());
Assert.assertEquals(customerOne.getPassword(), customerAfter.getPassword());
Assert.assertEquals(customerOne.getEmail(), customerAfter.getEmail());
}
@Test
public void testAuthenticateCustomer() throws ParseException {
//Customers
final Customer customerOne = new Customer(0, "Bauke", "Mollema", "BM", "BM123", "[email protected]");
final Customer customerTwo = new Customer(1, "Tom", "Dumoulin", "TD", "TD123", "[email protected]");
final Customer customerThree = new Customer(2, "Stef", "Clement", "SC", "SC123", "[email protected]");
//The no-customer test-user
final Customer noCustomer = new Customer(3, "Chris", "Froome", "CF", "CF123", "[email protected]");
//Putting all customers in a list
final List<Customer> dbCustomers = new ArrayList<>();
dbCustomers.add(0, customerOne);
dbCustomers.add(1, customerTwo);
dbCustomers.add(2, customerThree);
//Authentication control
Assert.assertEquals(customerOne ,generalService.authenticateCustomer(customerOne, dbCustomers));
Assert.assertEquals(customerTwo ,generalService.authenticateCustomer(customerTwo, dbCustomers));
Assert.assertEquals(customerThree ,generalService.authenticateCustomer(customerThree, dbCustomers));
Assert.assertNotEquals(noCustomer ,generalService.authenticateCustomer(noCustomer, dbCustomers));
}
@Test
public void testAuthenticateUser() {
final Customer testUser = null;
Assert.assertEquals(false, generalService.authenticateUser(testUser));
final Customer testCustomer = new Customer(1, "Marcel", "Groothuis", "Manollo7G", "secret", "[email protected]");
Assert.assertEquals(true, generalService.authenticateUser(testCustomer));
}
@Test
public void testGenerateShowTableWithEmptyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> emptyTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
final List<Show> testShows = new ArrayList<>();
final List<Movie> testMovies = new ArrayList<>();
//todaysShowsTable vullen met lege shows en movies.
emptyTodaysShowsTable = generalService.generateShowTable(testShows, testMovies);
//Check eerste unittest
Assert.assertEquals(emptyTodaysShowsTable, generalService.generateShowTable(testShows, testMovies));
Assert.assertEquals(0, emptyTodaysShowsTable.size());
}
@Test
public void testGenerateShowTableWithDerbyShowsAndMovies() throws ParseException, MovieNotFoundException {
List<ShowsPresentationVO> filledTodaysShowsTable = new ArrayList<ShowsPresentationVO>();
//Tweede unittest: lijsten maken met derby vulling After
final List<Show> shows = generalService.getShows();
final List<Movie> movies = generalService.getMovies();
//de todaysShowsTable vullen met de lege shows en movies.
filledTodaysShowsTable = generalService.generateShowTable(shows, movies);
//voorstellingen in<SUF>
ShowsPresentationVO TheLegendOfTarzan = null;
ShowsPresentationVO TarzanTheApeMan = null;
ShowsPresentationVO Tarzan = null;
ShowsPresentationVO WeddingCrashers = null;
ShowsPresentationVO BloodDiamond = null;
ShowsPresentationVO TheLionKing = null;
ShowsPresentationVO Snatch = null;
for (ShowsPresentationVO showsPresentationVO : filledTodaysShowsTable){
if(1 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLegendOfTarzan = showsPresentationVO;
}else if(2 == showsPresentationVO.getMovie().getMovieId().intValue()){
TarzanTheApeMan = showsPresentationVO;
}else if(3 == showsPresentationVO.getMovie().getMovieId().intValue()){
Tarzan = showsPresentationVO;
}else if(4 == showsPresentationVO.getMovie().getMovieId().intValue()){
WeddingCrashers = showsPresentationVO;
}else if(5 == showsPresentationVO.getMovie().getMovieId().intValue()){
BloodDiamond = showsPresentationVO;
}else if(6 == showsPresentationVO.getMovie().getMovieId().intValue()){
TheLionKing = showsPresentationVO;
}else if(7 == showsPresentationVO.getMovie().getMovieId().intValue()){
Snatch = showsPresentationVO;
}
}
Assert.assertEquals(filledTodaysShowsTable.size(), generalService.generateShowTable(shows, movies).size());
Assert.assertEquals(4, filledTodaysShowsTable.size());
Assert.assertEquals(1, TheLegendOfTarzan.getMovie().getMovieId().intValue());
Assert.assertEquals("The Legend of Tarzan (2016)", TheLegendOfTarzan.getMovie().getTitle());
Assert.assertEquals(1, TheLegendOfTarzan.getShowsPresentationVO().size());
Assert.assertEquals(2, TarzanTheApeMan.getMovie().getMovieId().intValue());
Assert.assertEquals("Tarzan the Ape Man (1932)", TarzanTheApeMan.getMovie().getTitle());
Assert.assertEquals(3, TarzanTheApeMan.getShowsPresentationVO().size());
Assert.assertEquals(4, WeddingCrashers.getMovie().getMovieId().intValue());
Assert.assertEquals("Wedding Crashers", WeddingCrashers.getMovie().getTitle());
Assert.assertEquals(1, WeddingCrashers.getShowsPresentationVO().size());
Assert.assertEquals(5, BloodDiamond.getMovie().getMovieId().intValue());
Assert.assertEquals("Blood Diamond", BloodDiamond.getMovie().getTitle());
Assert.assertEquals(2, BloodDiamond.getShowsPresentationVO().size());
Assert.assertNull(Tarzan);
Assert.assertNull(TheLionKing);
Assert.assertNull(Snatch);
}
private Customer getCustomer(final int customerID) {
return generalService.getCustomers().stream()
.filter(c -> c.getCustomerId() == customerID)
.findAny()
.orElse(null);
}
}
|
209699_18 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| sgano/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,350 | // Height, density parameters | line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density<SUF>
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209699_20 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| sgano/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,350 | // Satellite height (in km) | line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height<SUF>
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209699_30 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| sgano/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,350 | // loop over N_Coef height regimes | line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over<SUF>
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209703_26 |
package edu.vanderbilt.vm.guide.container;
//Credit to Sjaak Priester ( mailto:[email protected] )
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class Graph extends ArrayList<Node> {
private static final Logger logger = LoggerFactory.getLogger("container.Graph");
public Node getNodeWithLowestScore() {
double score = Double.MAX_VALUE;
Node lowest = null;
for (Node node : this) {
if (node.getScore() < score) {
score = node.getScore();
lowest = node;
}
}
return lowest;
}
public Graph getNodeNeighbour(Node n) {
Graph graph = new Graph();
if (!this.contains(n)) {
return graph;
}
for (int id : n.getNeighbours()) {
Node nn = this.findNodeById(id);
if (nn != null) {
graph.add(nn);
}
}
return null;
}
public Node findNodeById(int id) {
for (Node n : this) {
if (n.getId() == id) {
return n;
}
}
return null;
}
public static Graph createGraph(Agenda a) {
Graph g = new Graph();
for (Place plc : a) {
g.add(new Node(plc));
}
return g;
}
public Graph findPath(Node start, Node end) {
// Assert that "start" and "end" are elements of "g"
// Assert that Graph is a typedef of Arraylist<Node>
// Initialization routine
for (Node node : this) {
if (node.getId() == start.getId()) {
node.setScore(0);
} else {
node.setScore(Double.MAX_VALUE);
}
node.setPrevious(-1);
}
// Create a set of nodes not yet examined. This initially contain all
// the nodes in "g"
Graph unvisited = (Graph)this.clone();
// This is the bulk of the algorithm
while (!unvisited.isEmpty()) {
Node u = unvisited.getNodeWithLowestScore();
unvisited.remove(u);
if (u.getId() == end.getId()) {
break;
}
if (u.getScore() == Double.MAX_VALUE) {
break;
}
for (Node neigh : this.getNodeNeighbour(u)) {
// getNeighbours() returns a Graph object
if (!unvisited.contains(neigh)) {
continue;
}
double dist = u.getScore() + u.distanceTo(neigh);
if (dist < neigh.getScore()) {
neigh.setScore(dist);
neigh.setPrevious(u.getId());
}
}
}
// backtracing the path
// Since "start" and "end" are elements of "g", They should have
// received
// the result of the algorithm run
Graph path = new Graph();
int prev = end.getPrevious();
while (prev != -1) {
path.add(this.findNodeById(prev));
prev = (this.findNodeById(prev)).getPrevious();
}
return path;
}
/**
* Given a graph which contain a set of at least three points, build
* adjacency list for each Nodes according to the rules laid out by the
* Delaunay Triangulation. Adapted from an implementation by Sjaak Priester
* ( mailto:[email protected] )
*/
public void buildNetwork() {
if (this.size() < 2) {
logger.debug("Can't build network with less than 2 points");
return;
}
if (this.size() < 3) {
this.get(0).addNeighbour(this.get(1).getId());
this.get(1).addNeighbour(this.get(0).getId());
logger.debug("Can't build triangle with less than 3 points");
return;
}
// Initialization
ArrayList<Triangle> workingSet = new ArrayList<Triangle>();
Collections.sort(this, new HorizontalComparator());
ArrayList<Triangle> finishedSet = new ArrayList<Triangle>();
// Find bounding rectangle
double xMin = this.get(0).getLng();
double yMin = this.get(0).getLat();
double xMax = xMin;
double yMax = yMin;
for (Node n : this) {
if (n.getLng() > xMax) {
xMax = n.getLng();
}
if (n.getLat() > yMax) {
yMax = n.getLat();
}
if (n.getLat() < yMin) {
yMin = n.getLat();
}
}
// Give a little padding to the bounding rectangle
yMax += 2 * Node.EPSILON;
xMax += 2 * Node.EPSILON;
yMin -= 2 * Node.EPSILON;
xMin -= 2 * Node.EPSILON;
double h = yMax - yMin;
double w = xMax - xMin;
// logger.debug("Bounding Rect: " + xMin + " " + xMax + " " + yMin + " "
// + yMax + " " + h + " " + w );
// Create supertriangle that encompasses all Nodes
Triangle superTri = new Triangle();
superTri.add(new Node(-1, yMin, xMin - w, null));
superTri.add(new Node(-2, yMin, xMax + w, null));
superTri.add(new Node(-3, yMax + h, (xMin + xMax) / 2, null));
workingSet.add(superTri);
// [Delaunaaaaaaaaaaaay]
// Add each nodes in this Graph one by one.
// Each node is guaranteed to be inside a Triangle, due to the
// super Triangle.
// For each addition, find a list of triangles that encompasses the
// node. Remove the Triangle but keep its edges in an edgebuffer.
// Remove duplicate Edges, then build new triangles from each edge to
// the Node being added
ArrayList<Edge> edgeSet = new ArrayList<Edge>();
for (Node n : this) {
// Search for Triangles that contain this Vertex
// store its edges, and then remove the Triangle
edgeSet.clear();
//logger.debug("Size of workingSet before remove: " + workingSet.size());
for (int k = 0; k < workingSet.size(); k++) {
Triangle tri = workingSet.get(k);
if (tri.isLeftOf(n)) {
// should move completed triangle to the finished set
finishedSet.add(tri);
workingSet.remove(k);
k--;
} else if (tri.isEncompassing(n)) {
edgeSet.add(new Edge(tri.get(0), tri.get(1)));
edgeSet.add(new Edge(tri.get(1), tri.get(2)));
edgeSet.add(new Edge(tri.get(0), tri.get(2)));
workingSet.remove(k);
k--;
} else {
// logger.debug("Not encompassing");
}
}
// logger.debug("Size of workingSet after remove: " + workingSet.size());
// logger.debug("Size of edgeSet before remove: " + edgeSet.size());
removeDuplicateEdge(edgeSet);
// logger.debug("Size of edgeSet after remove: " + edgeSet.size());
for (Edge e : edgeSet) {
Triangle newT = new Triangle();
newT.add(e.get(0));
newT.add(e.get(1));
newT.add(n);
workingSet.add(newT);
}
}
// Remove super triangle
workingSet.remove(superTri);
// Add all remaining Triangles to the finished set
for (Triangle tri : workingSet) {
finishedSet.add(tri);
}
workingSet = null;
// logger.debug("Size of workingSet: " + workingSet.size());
// convert to adjacency list
for (Triangle tri : finishedSet) {
// logger.debug("Id: "+tri.get(0).getId());
if ( (tri.get(0).getId() <= 0) ||
(tri.get(1).getId() <= 0) ||
(tri.get(2).getId() <= 0)) {
continue;
}
Node nn = this.findNodeById(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(1).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(2).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
}
}
private class HorizontalComparator implements Comparator<Node> {
@Override
public int compare(Node n1, Node n2) {
return (n1.getLng() > n2.getLng()) ? 1 : -1;
}
}
private void removeDuplicateEdge(ArrayList<Edge> edgeSet) {
for (int i = 0; i < edgeSet.size() - 1; i++) {
for (int j = i + 1; j < edgeSet.size(); j++) {
if ((edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(0).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(1).getId())
|| (edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(1).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(0).getId())) {
// Remove duplicate
edgeSet.remove(j);
edgeSet.remove(i);
i--;
break;
}
}
}
}
private static class Edge extends ArrayList<Node> {
public Edge(Node n1, Node n2) {
this.add(n1);
this.add(n2);
}
}
static class Triangle extends ArrayList<Node> {
private Node mCentre;
private double mRad;
// private static final Logger logger =
// LoggerFactory.getLogger("container.Triangle");
@Override
public boolean add(Node n) {
if (this.size() > 3) {
throw new IllegalStateException("Can't add more than three " + "Nodes to Triangle.");
}
super.add(n);
if (this.size() == 3) {
calculateCircle();
// logger.debug("This triangle has " + mCentre.getLat() + " " +
// mCentre.getLng() + " " + mRad);
}
return true;
}
@Override
public Node get(int index) {
if (index > 3) {
throw new IllegalStateException("A triangle has only three points");
}
return super.get(index);
}
public boolean isEncompassing(Node n) {
// logger.debug("Values for isEncompassing: "+n.naiveDist(mCentre)+" "+mRad
// );
return n.naiveDist(mCentre) <= mRad;
}
private void calculateCircle() {
mCentre = new Node(0, 0);
double x1 = this.get(0).getLng();
double y1 = this.get(0).getLat();
double x2 = this.get(1).getLng();
double y2 = this.get(1).getLat();
double x3 = this.get(2).getLng();
double y3 = this.get(2).getLat();
double dy21 = y2 - y1;
double dy32 = y3 - y2;
// logger.debug("Values: " + x1 + " " + y1 + " " + x2 + " " + y2 +
// " " + x3 + " " + y3 );
// Checking for edge cases
// Mostly to prevent division by zero
if (isZero(dy21) && isZero(dy32)) {
// All three are on the same horizontal line
if (x2 > x1) {
if (x3 > x2) {
x2 = x3;
}
} else if (x3 < x1) {
x1 = x3;
}
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(y1);
// logger.debug("branch 1");
} else if (isZero(dy21)) {
// Node1 and Node2 are on the same horizontal line
// logger.debug("branch 2: " + dy21 + " " +dy32);
double m1 = -(x3 - x2) / dy32;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(m1 * (mCentre.getLng() - mx1) + my1);
// logger.debug("branch 2: " + mCentre.getLat() + " " +
// mCentre.getLng());
} else if (isZero(dy32)) {
// Node2 and Node3 are on the same horizontal line
double m0 = -(x2 - x1) / dy21;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
mCentre.setLng((x2 + x3) / 2);
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 3");
// Common case. No Nodes are on the same horizontal line
} else {
double m0 = -(x2 - x1) / dy21;
double m1 = -(x3 - x2) / dy32;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((m0 * mx0 - m1 * mx1 + my1 - my0) / (m0 - m1));
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 4");
}
// Calculating circle's radius
double rx = x3 - mCentre.getLng();
double ry = y3 - mCentre.getLat();
double r2 = rx * rx + ry * ry;
mRad = Math.sqrt(r2);
// make the radius slightly bigger
mRad = mRad + 2 * Node.EPSILON;
}
private boolean isZero(double d) {
return Math.abs(d) < Node.EPSILON;
}
public boolean isLeftOf(Node n) {
return n.getLng() > (mCentre.getLng() + mRad);
}
}
}
| VandyApps/guide-android | GuideAndroid/src/edu/vanderbilt/vm/guide/container/Graph.java | 3,947 | // logger.debug("Size of workingSet after remove: " + workingSet.size()); | line_comment | nl |
package edu.vanderbilt.vm.guide.container;
//Credit to Sjaak Priester ( mailto:[email protected] )
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class Graph extends ArrayList<Node> {
private static final Logger logger = LoggerFactory.getLogger("container.Graph");
public Node getNodeWithLowestScore() {
double score = Double.MAX_VALUE;
Node lowest = null;
for (Node node : this) {
if (node.getScore() < score) {
score = node.getScore();
lowest = node;
}
}
return lowest;
}
public Graph getNodeNeighbour(Node n) {
Graph graph = new Graph();
if (!this.contains(n)) {
return graph;
}
for (int id : n.getNeighbours()) {
Node nn = this.findNodeById(id);
if (nn != null) {
graph.add(nn);
}
}
return null;
}
public Node findNodeById(int id) {
for (Node n : this) {
if (n.getId() == id) {
return n;
}
}
return null;
}
public static Graph createGraph(Agenda a) {
Graph g = new Graph();
for (Place plc : a) {
g.add(new Node(plc));
}
return g;
}
public Graph findPath(Node start, Node end) {
// Assert that "start" and "end" are elements of "g"
// Assert that Graph is a typedef of Arraylist<Node>
// Initialization routine
for (Node node : this) {
if (node.getId() == start.getId()) {
node.setScore(0);
} else {
node.setScore(Double.MAX_VALUE);
}
node.setPrevious(-1);
}
// Create a set of nodes not yet examined. This initially contain all
// the nodes in "g"
Graph unvisited = (Graph)this.clone();
// This is the bulk of the algorithm
while (!unvisited.isEmpty()) {
Node u = unvisited.getNodeWithLowestScore();
unvisited.remove(u);
if (u.getId() == end.getId()) {
break;
}
if (u.getScore() == Double.MAX_VALUE) {
break;
}
for (Node neigh : this.getNodeNeighbour(u)) {
// getNeighbours() returns a Graph object
if (!unvisited.contains(neigh)) {
continue;
}
double dist = u.getScore() + u.distanceTo(neigh);
if (dist < neigh.getScore()) {
neigh.setScore(dist);
neigh.setPrevious(u.getId());
}
}
}
// backtracing the path
// Since "start" and "end" are elements of "g", They should have
// received
// the result of the algorithm run
Graph path = new Graph();
int prev = end.getPrevious();
while (prev != -1) {
path.add(this.findNodeById(prev));
prev = (this.findNodeById(prev)).getPrevious();
}
return path;
}
/**
* Given a graph which contain a set of at least three points, build
* adjacency list for each Nodes according to the rules laid out by the
* Delaunay Triangulation. Adapted from an implementation by Sjaak Priester
* ( mailto:[email protected] )
*/
public void buildNetwork() {
if (this.size() < 2) {
logger.debug("Can't build network with less than 2 points");
return;
}
if (this.size() < 3) {
this.get(0).addNeighbour(this.get(1).getId());
this.get(1).addNeighbour(this.get(0).getId());
logger.debug("Can't build triangle with less than 3 points");
return;
}
// Initialization
ArrayList<Triangle> workingSet = new ArrayList<Triangle>();
Collections.sort(this, new HorizontalComparator());
ArrayList<Triangle> finishedSet = new ArrayList<Triangle>();
// Find bounding rectangle
double xMin = this.get(0).getLng();
double yMin = this.get(0).getLat();
double xMax = xMin;
double yMax = yMin;
for (Node n : this) {
if (n.getLng() > xMax) {
xMax = n.getLng();
}
if (n.getLat() > yMax) {
yMax = n.getLat();
}
if (n.getLat() < yMin) {
yMin = n.getLat();
}
}
// Give a little padding to the bounding rectangle
yMax += 2 * Node.EPSILON;
xMax += 2 * Node.EPSILON;
yMin -= 2 * Node.EPSILON;
xMin -= 2 * Node.EPSILON;
double h = yMax - yMin;
double w = xMax - xMin;
// logger.debug("Bounding Rect: " + xMin + " " + xMax + " " + yMin + " "
// + yMax + " " + h + " " + w );
// Create supertriangle that encompasses all Nodes
Triangle superTri = new Triangle();
superTri.add(new Node(-1, yMin, xMin - w, null));
superTri.add(new Node(-2, yMin, xMax + w, null));
superTri.add(new Node(-3, yMax + h, (xMin + xMax) / 2, null));
workingSet.add(superTri);
// [Delaunaaaaaaaaaaaay]
// Add each nodes in this Graph one by one.
// Each node is guaranteed to be inside a Triangle, due to the
// super Triangle.
// For each addition, find a list of triangles that encompasses the
// node. Remove the Triangle but keep its edges in an edgebuffer.
// Remove duplicate Edges, then build new triangles from each edge to
// the Node being added
ArrayList<Edge> edgeSet = new ArrayList<Edge>();
for (Node n : this) {
// Search for Triangles that contain this Vertex
// store its edges, and then remove the Triangle
edgeSet.clear();
//logger.debug("Size of workingSet before remove: " + workingSet.size());
for (int k = 0; k < workingSet.size(); k++) {
Triangle tri = workingSet.get(k);
if (tri.isLeftOf(n)) {
// should move completed triangle to the finished set
finishedSet.add(tri);
workingSet.remove(k);
k--;
} else if (tri.isEncompassing(n)) {
edgeSet.add(new Edge(tri.get(0), tri.get(1)));
edgeSet.add(new Edge(tri.get(1), tri.get(2)));
edgeSet.add(new Edge(tri.get(0), tri.get(2)));
workingSet.remove(k);
k--;
} else {
// logger.debug("Not encompassing");
}
}
// logger.debug("Size of<SUF>
// logger.debug("Size of edgeSet before remove: " + edgeSet.size());
removeDuplicateEdge(edgeSet);
// logger.debug("Size of edgeSet after remove: " + edgeSet.size());
for (Edge e : edgeSet) {
Triangle newT = new Triangle();
newT.add(e.get(0));
newT.add(e.get(1));
newT.add(n);
workingSet.add(newT);
}
}
// Remove super triangle
workingSet.remove(superTri);
// Add all remaining Triangles to the finished set
for (Triangle tri : workingSet) {
finishedSet.add(tri);
}
workingSet = null;
// logger.debug("Size of workingSet: " + workingSet.size());
// convert to adjacency list
for (Triangle tri : finishedSet) {
// logger.debug("Id: "+tri.get(0).getId());
if ( (tri.get(0).getId() <= 0) ||
(tri.get(1).getId() <= 0) ||
(tri.get(2).getId() <= 0)) {
continue;
}
Node nn = this.findNodeById(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(1).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(2).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
}
}
private class HorizontalComparator implements Comparator<Node> {
@Override
public int compare(Node n1, Node n2) {
return (n1.getLng() > n2.getLng()) ? 1 : -1;
}
}
private void removeDuplicateEdge(ArrayList<Edge> edgeSet) {
for (int i = 0; i < edgeSet.size() - 1; i++) {
for (int j = i + 1; j < edgeSet.size(); j++) {
if ((edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(0).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(1).getId())
|| (edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(1).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(0).getId())) {
// Remove duplicate
edgeSet.remove(j);
edgeSet.remove(i);
i--;
break;
}
}
}
}
private static class Edge extends ArrayList<Node> {
public Edge(Node n1, Node n2) {
this.add(n1);
this.add(n2);
}
}
static class Triangle extends ArrayList<Node> {
private Node mCentre;
private double mRad;
// private static final Logger logger =
// LoggerFactory.getLogger("container.Triangle");
@Override
public boolean add(Node n) {
if (this.size() > 3) {
throw new IllegalStateException("Can't add more than three " + "Nodes to Triangle.");
}
super.add(n);
if (this.size() == 3) {
calculateCircle();
// logger.debug("This triangle has " + mCentre.getLat() + " " +
// mCentre.getLng() + " " + mRad);
}
return true;
}
@Override
public Node get(int index) {
if (index > 3) {
throw new IllegalStateException("A triangle has only three points");
}
return super.get(index);
}
public boolean isEncompassing(Node n) {
// logger.debug("Values for isEncompassing: "+n.naiveDist(mCentre)+" "+mRad
// );
return n.naiveDist(mCentre) <= mRad;
}
private void calculateCircle() {
mCentre = new Node(0, 0);
double x1 = this.get(0).getLng();
double y1 = this.get(0).getLat();
double x2 = this.get(1).getLng();
double y2 = this.get(1).getLat();
double x3 = this.get(2).getLng();
double y3 = this.get(2).getLat();
double dy21 = y2 - y1;
double dy32 = y3 - y2;
// logger.debug("Values: " + x1 + " " + y1 + " " + x2 + " " + y2 +
// " " + x3 + " " + y3 );
// Checking for edge cases
// Mostly to prevent division by zero
if (isZero(dy21) && isZero(dy32)) {
// All three are on the same horizontal line
if (x2 > x1) {
if (x3 > x2) {
x2 = x3;
}
} else if (x3 < x1) {
x1 = x3;
}
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(y1);
// logger.debug("branch 1");
} else if (isZero(dy21)) {
// Node1 and Node2 are on the same horizontal line
// logger.debug("branch 2: " + dy21 + " " +dy32);
double m1 = -(x3 - x2) / dy32;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(m1 * (mCentre.getLng() - mx1) + my1);
// logger.debug("branch 2: " + mCentre.getLat() + " " +
// mCentre.getLng());
} else if (isZero(dy32)) {
// Node2 and Node3 are on the same horizontal line
double m0 = -(x2 - x1) / dy21;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
mCentre.setLng((x2 + x3) / 2);
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 3");
// Common case. No Nodes are on the same horizontal line
} else {
double m0 = -(x2 - x1) / dy21;
double m1 = -(x3 - x2) / dy32;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((m0 * mx0 - m1 * mx1 + my1 - my0) / (m0 - m1));
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 4");
}
// Calculating circle's radius
double rx = x3 - mCentre.getLng();
double ry = y3 - mCentre.getLat();
double r2 = rx * rx + ry * ry;
mRad = Math.sqrt(r2);
// make the radius slightly bigger
mRad = mRad + 2 * Node.EPSILON;
}
private boolean isZero(double d) {
return Math.abs(d) < Node.EPSILON;
}
public boolean isLeftOf(Node n) {
return n.getLng() > (mCentre.getLng() + mRad);
}
}
}
|
209703_35 |
package edu.vanderbilt.vm.guide.container;
//Credit to Sjaak Priester ( mailto:[email protected] )
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class Graph extends ArrayList<Node> {
private static final Logger logger = LoggerFactory.getLogger("container.Graph");
public Node getNodeWithLowestScore() {
double score = Double.MAX_VALUE;
Node lowest = null;
for (Node node : this) {
if (node.getScore() < score) {
score = node.getScore();
lowest = node;
}
}
return lowest;
}
public Graph getNodeNeighbour(Node n) {
Graph graph = new Graph();
if (!this.contains(n)) {
return graph;
}
for (int id : n.getNeighbours()) {
Node nn = this.findNodeById(id);
if (nn != null) {
graph.add(nn);
}
}
return null;
}
public Node findNodeById(int id) {
for (Node n : this) {
if (n.getId() == id) {
return n;
}
}
return null;
}
public static Graph createGraph(Agenda a) {
Graph g = new Graph();
for (Place plc : a) {
g.add(new Node(plc));
}
return g;
}
public Graph findPath(Node start, Node end) {
// Assert that "start" and "end" are elements of "g"
// Assert that Graph is a typedef of Arraylist<Node>
// Initialization routine
for (Node node : this) {
if (node.getId() == start.getId()) {
node.setScore(0);
} else {
node.setScore(Double.MAX_VALUE);
}
node.setPrevious(-1);
}
// Create a set of nodes not yet examined. This initially contain all
// the nodes in "g"
Graph unvisited = (Graph)this.clone();
// This is the bulk of the algorithm
while (!unvisited.isEmpty()) {
Node u = unvisited.getNodeWithLowestScore();
unvisited.remove(u);
if (u.getId() == end.getId()) {
break;
}
if (u.getScore() == Double.MAX_VALUE) {
break;
}
for (Node neigh : this.getNodeNeighbour(u)) {
// getNeighbours() returns a Graph object
if (!unvisited.contains(neigh)) {
continue;
}
double dist = u.getScore() + u.distanceTo(neigh);
if (dist < neigh.getScore()) {
neigh.setScore(dist);
neigh.setPrevious(u.getId());
}
}
}
// backtracing the path
// Since "start" and "end" are elements of "g", They should have
// received
// the result of the algorithm run
Graph path = new Graph();
int prev = end.getPrevious();
while (prev != -1) {
path.add(this.findNodeById(prev));
prev = (this.findNodeById(prev)).getPrevious();
}
return path;
}
/**
* Given a graph which contain a set of at least three points, build
* adjacency list for each Nodes according to the rules laid out by the
* Delaunay Triangulation. Adapted from an implementation by Sjaak Priester
* ( mailto:[email protected] )
*/
public void buildNetwork() {
if (this.size() < 2) {
logger.debug("Can't build network with less than 2 points");
return;
}
if (this.size() < 3) {
this.get(0).addNeighbour(this.get(1).getId());
this.get(1).addNeighbour(this.get(0).getId());
logger.debug("Can't build triangle with less than 3 points");
return;
}
// Initialization
ArrayList<Triangle> workingSet = new ArrayList<Triangle>();
Collections.sort(this, new HorizontalComparator());
ArrayList<Triangle> finishedSet = new ArrayList<Triangle>();
// Find bounding rectangle
double xMin = this.get(0).getLng();
double yMin = this.get(0).getLat();
double xMax = xMin;
double yMax = yMin;
for (Node n : this) {
if (n.getLng() > xMax) {
xMax = n.getLng();
}
if (n.getLat() > yMax) {
yMax = n.getLat();
}
if (n.getLat() < yMin) {
yMin = n.getLat();
}
}
// Give a little padding to the bounding rectangle
yMax += 2 * Node.EPSILON;
xMax += 2 * Node.EPSILON;
yMin -= 2 * Node.EPSILON;
xMin -= 2 * Node.EPSILON;
double h = yMax - yMin;
double w = xMax - xMin;
// logger.debug("Bounding Rect: " + xMin + " " + xMax + " " + yMin + " "
// + yMax + " " + h + " " + w );
// Create supertriangle that encompasses all Nodes
Triangle superTri = new Triangle();
superTri.add(new Node(-1, yMin, xMin - w, null));
superTri.add(new Node(-2, yMin, xMax + w, null));
superTri.add(new Node(-3, yMax + h, (xMin + xMax) / 2, null));
workingSet.add(superTri);
// [Delaunaaaaaaaaaaaay]
// Add each nodes in this Graph one by one.
// Each node is guaranteed to be inside a Triangle, due to the
// super Triangle.
// For each addition, find a list of triangles that encompasses the
// node. Remove the Triangle but keep its edges in an edgebuffer.
// Remove duplicate Edges, then build new triangles from each edge to
// the Node being added
ArrayList<Edge> edgeSet = new ArrayList<Edge>();
for (Node n : this) {
// Search for Triangles that contain this Vertex
// store its edges, and then remove the Triangle
edgeSet.clear();
//logger.debug("Size of workingSet before remove: " + workingSet.size());
for (int k = 0; k < workingSet.size(); k++) {
Triangle tri = workingSet.get(k);
if (tri.isLeftOf(n)) {
// should move completed triangle to the finished set
finishedSet.add(tri);
workingSet.remove(k);
k--;
} else if (tri.isEncompassing(n)) {
edgeSet.add(new Edge(tri.get(0), tri.get(1)));
edgeSet.add(new Edge(tri.get(1), tri.get(2)));
edgeSet.add(new Edge(tri.get(0), tri.get(2)));
workingSet.remove(k);
k--;
} else {
// logger.debug("Not encompassing");
}
}
// logger.debug("Size of workingSet after remove: " + workingSet.size());
// logger.debug("Size of edgeSet before remove: " + edgeSet.size());
removeDuplicateEdge(edgeSet);
// logger.debug("Size of edgeSet after remove: " + edgeSet.size());
for (Edge e : edgeSet) {
Triangle newT = new Triangle();
newT.add(e.get(0));
newT.add(e.get(1));
newT.add(n);
workingSet.add(newT);
}
}
// Remove super triangle
workingSet.remove(superTri);
// Add all remaining Triangles to the finished set
for (Triangle tri : workingSet) {
finishedSet.add(tri);
}
workingSet = null;
// logger.debug("Size of workingSet: " + workingSet.size());
// convert to adjacency list
for (Triangle tri : finishedSet) {
// logger.debug("Id: "+tri.get(0).getId());
if ( (tri.get(0).getId() <= 0) ||
(tri.get(1).getId() <= 0) ||
(tri.get(2).getId() <= 0)) {
continue;
}
Node nn = this.findNodeById(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(1).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(2).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
}
}
private class HorizontalComparator implements Comparator<Node> {
@Override
public int compare(Node n1, Node n2) {
return (n1.getLng() > n2.getLng()) ? 1 : -1;
}
}
private void removeDuplicateEdge(ArrayList<Edge> edgeSet) {
for (int i = 0; i < edgeSet.size() - 1; i++) {
for (int j = i + 1; j < edgeSet.size(); j++) {
if ((edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(0).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(1).getId())
|| (edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(1).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(0).getId())) {
// Remove duplicate
edgeSet.remove(j);
edgeSet.remove(i);
i--;
break;
}
}
}
}
private static class Edge extends ArrayList<Node> {
public Edge(Node n1, Node n2) {
this.add(n1);
this.add(n2);
}
}
static class Triangle extends ArrayList<Node> {
private Node mCentre;
private double mRad;
// private static final Logger logger =
// LoggerFactory.getLogger("container.Triangle");
@Override
public boolean add(Node n) {
if (this.size() > 3) {
throw new IllegalStateException("Can't add more than three " + "Nodes to Triangle.");
}
super.add(n);
if (this.size() == 3) {
calculateCircle();
// logger.debug("This triangle has " + mCentre.getLat() + " " +
// mCentre.getLng() + " " + mRad);
}
return true;
}
@Override
public Node get(int index) {
if (index > 3) {
throw new IllegalStateException("A triangle has only three points");
}
return super.get(index);
}
public boolean isEncompassing(Node n) {
// logger.debug("Values for isEncompassing: "+n.naiveDist(mCentre)+" "+mRad
// );
return n.naiveDist(mCentre) <= mRad;
}
private void calculateCircle() {
mCentre = new Node(0, 0);
double x1 = this.get(0).getLng();
double y1 = this.get(0).getLat();
double x2 = this.get(1).getLng();
double y2 = this.get(1).getLat();
double x3 = this.get(2).getLng();
double y3 = this.get(2).getLat();
double dy21 = y2 - y1;
double dy32 = y3 - y2;
// logger.debug("Values: " + x1 + " " + y1 + " " + x2 + " " + y2 +
// " " + x3 + " " + y3 );
// Checking for edge cases
// Mostly to prevent division by zero
if (isZero(dy21) && isZero(dy32)) {
// All three are on the same horizontal line
if (x2 > x1) {
if (x3 > x2) {
x2 = x3;
}
} else if (x3 < x1) {
x1 = x3;
}
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(y1);
// logger.debug("branch 1");
} else if (isZero(dy21)) {
// Node1 and Node2 are on the same horizontal line
// logger.debug("branch 2: " + dy21 + " " +dy32);
double m1 = -(x3 - x2) / dy32;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(m1 * (mCentre.getLng() - mx1) + my1);
// logger.debug("branch 2: " + mCentre.getLat() + " " +
// mCentre.getLng());
} else if (isZero(dy32)) {
// Node2 and Node3 are on the same horizontal line
double m0 = -(x2 - x1) / dy21;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
mCentre.setLng((x2 + x3) / 2);
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 3");
// Common case. No Nodes are on the same horizontal line
} else {
double m0 = -(x2 - x1) / dy21;
double m1 = -(x3 - x2) / dy32;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((m0 * mx0 - m1 * mx1 + my1 - my0) / (m0 - m1));
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 4");
}
// Calculating circle's radius
double rx = x3 - mCentre.getLng();
double ry = y3 - mCentre.getLat();
double r2 = rx * rx + ry * ry;
mRad = Math.sqrt(r2);
// make the radius slightly bigger
mRad = mRad + 2 * Node.EPSILON;
}
private boolean isZero(double d) {
return Math.abs(d) < Node.EPSILON;
}
public boolean isLeftOf(Node n) {
return n.getLng() > (mCentre.getLng() + mRad);
}
}
}
| VandyApps/guide-android | GuideAndroid/src/edu/vanderbilt/vm/guide/container/Graph.java | 3,947 | // mCentre.getLng() + " " + mRad); | line_comment | nl |
package edu.vanderbilt.vm.guide.container;
//Credit to Sjaak Priester ( mailto:[email protected] )
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class Graph extends ArrayList<Node> {
private static final Logger logger = LoggerFactory.getLogger("container.Graph");
public Node getNodeWithLowestScore() {
double score = Double.MAX_VALUE;
Node lowest = null;
for (Node node : this) {
if (node.getScore() < score) {
score = node.getScore();
lowest = node;
}
}
return lowest;
}
public Graph getNodeNeighbour(Node n) {
Graph graph = new Graph();
if (!this.contains(n)) {
return graph;
}
for (int id : n.getNeighbours()) {
Node nn = this.findNodeById(id);
if (nn != null) {
graph.add(nn);
}
}
return null;
}
public Node findNodeById(int id) {
for (Node n : this) {
if (n.getId() == id) {
return n;
}
}
return null;
}
public static Graph createGraph(Agenda a) {
Graph g = new Graph();
for (Place plc : a) {
g.add(new Node(plc));
}
return g;
}
public Graph findPath(Node start, Node end) {
// Assert that "start" and "end" are elements of "g"
// Assert that Graph is a typedef of Arraylist<Node>
// Initialization routine
for (Node node : this) {
if (node.getId() == start.getId()) {
node.setScore(0);
} else {
node.setScore(Double.MAX_VALUE);
}
node.setPrevious(-1);
}
// Create a set of nodes not yet examined. This initially contain all
// the nodes in "g"
Graph unvisited = (Graph)this.clone();
// This is the bulk of the algorithm
while (!unvisited.isEmpty()) {
Node u = unvisited.getNodeWithLowestScore();
unvisited.remove(u);
if (u.getId() == end.getId()) {
break;
}
if (u.getScore() == Double.MAX_VALUE) {
break;
}
for (Node neigh : this.getNodeNeighbour(u)) {
// getNeighbours() returns a Graph object
if (!unvisited.contains(neigh)) {
continue;
}
double dist = u.getScore() + u.distanceTo(neigh);
if (dist < neigh.getScore()) {
neigh.setScore(dist);
neigh.setPrevious(u.getId());
}
}
}
// backtracing the path
// Since "start" and "end" are elements of "g", They should have
// received
// the result of the algorithm run
Graph path = new Graph();
int prev = end.getPrevious();
while (prev != -1) {
path.add(this.findNodeById(prev));
prev = (this.findNodeById(prev)).getPrevious();
}
return path;
}
/**
* Given a graph which contain a set of at least three points, build
* adjacency list for each Nodes according to the rules laid out by the
* Delaunay Triangulation. Adapted from an implementation by Sjaak Priester
* ( mailto:[email protected] )
*/
public void buildNetwork() {
if (this.size() < 2) {
logger.debug("Can't build network with less than 2 points");
return;
}
if (this.size() < 3) {
this.get(0).addNeighbour(this.get(1).getId());
this.get(1).addNeighbour(this.get(0).getId());
logger.debug("Can't build triangle with less than 3 points");
return;
}
// Initialization
ArrayList<Triangle> workingSet = new ArrayList<Triangle>();
Collections.sort(this, new HorizontalComparator());
ArrayList<Triangle> finishedSet = new ArrayList<Triangle>();
// Find bounding rectangle
double xMin = this.get(0).getLng();
double yMin = this.get(0).getLat();
double xMax = xMin;
double yMax = yMin;
for (Node n : this) {
if (n.getLng() > xMax) {
xMax = n.getLng();
}
if (n.getLat() > yMax) {
yMax = n.getLat();
}
if (n.getLat() < yMin) {
yMin = n.getLat();
}
}
// Give a little padding to the bounding rectangle
yMax += 2 * Node.EPSILON;
xMax += 2 * Node.EPSILON;
yMin -= 2 * Node.EPSILON;
xMin -= 2 * Node.EPSILON;
double h = yMax - yMin;
double w = xMax - xMin;
// logger.debug("Bounding Rect: " + xMin + " " + xMax + " " + yMin + " "
// + yMax + " " + h + " " + w );
// Create supertriangle that encompasses all Nodes
Triangle superTri = new Triangle();
superTri.add(new Node(-1, yMin, xMin - w, null));
superTri.add(new Node(-2, yMin, xMax + w, null));
superTri.add(new Node(-3, yMax + h, (xMin + xMax) / 2, null));
workingSet.add(superTri);
// [Delaunaaaaaaaaaaaay]
// Add each nodes in this Graph one by one.
// Each node is guaranteed to be inside a Triangle, due to the
// super Triangle.
// For each addition, find a list of triangles that encompasses the
// node. Remove the Triangle but keep its edges in an edgebuffer.
// Remove duplicate Edges, then build new triangles from each edge to
// the Node being added
ArrayList<Edge> edgeSet = new ArrayList<Edge>();
for (Node n : this) {
// Search for Triangles that contain this Vertex
// store its edges, and then remove the Triangle
edgeSet.clear();
//logger.debug("Size of workingSet before remove: " + workingSet.size());
for (int k = 0; k < workingSet.size(); k++) {
Triangle tri = workingSet.get(k);
if (tri.isLeftOf(n)) {
// should move completed triangle to the finished set
finishedSet.add(tri);
workingSet.remove(k);
k--;
} else if (tri.isEncompassing(n)) {
edgeSet.add(new Edge(tri.get(0), tri.get(1)));
edgeSet.add(new Edge(tri.get(1), tri.get(2)));
edgeSet.add(new Edge(tri.get(0), tri.get(2)));
workingSet.remove(k);
k--;
} else {
// logger.debug("Not encompassing");
}
}
// logger.debug("Size of workingSet after remove: " + workingSet.size());
// logger.debug("Size of edgeSet before remove: " + edgeSet.size());
removeDuplicateEdge(edgeSet);
// logger.debug("Size of edgeSet after remove: " + edgeSet.size());
for (Edge e : edgeSet) {
Triangle newT = new Triangle();
newT.add(e.get(0));
newT.add(e.get(1));
newT.add(n);
workingSet.add(newT);
}
}
// Remove super triangle
workingSet.remove(superTri);
// Add all remaining Triangles to the finished set
for (Triangle tri : workingSet) {
finishedSet.add(tri);
}
workingSet = null;
// logger.debug("Size of workingSet: " + workingSet.size());
// convert to adjacency list
for (Triangle tri : finishedSet) {
// logger.debug("Id: "+tri.get(0).getId());
if ( (tri.get(0).getId() <= 0) ||
(tri.get(1).getId() <= 0) ||
(tri.get(2).getId() <= 0)) {
continue;
}
Node nn = this.findNodeById(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(1).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(2).getId());
nn = this.findNodeById(tri.get(2).getId());
nn.addNeighbour(tri.get(0).getId());
nn.addNeighbour(tri.get(1).getId());
}
}
private class HorizontalComparator implements Comparator<Node> {
@Override
public int compare(Node n1, Node n2) {
return (n1.getLng() > n2.getLng()) ? 1 : -1;
}
}
private void removeDuplicateEdge(ArrayList<Edge> edgeSet) {
for (int i = 0; i < edgeSet.size() - 1; i++) {
for (int j = i + 1; j < edgeSet.size(); j++) {
if ((edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(0).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(1).getId())
|| (edgeSet.get(i).get(0).getId() == edgeSet.get(j).get(1).getId() && edgeSet
.get(i).get(1).getId() == edgeSet.get(j).get(0).getId())) {
// Remove duplicate
edgeSet.remove(j);
edgeSet.remove(i);
i--;
break;
}
}
}
}
private static class Edge extends ArrayList<Node> {
public Edge(Node n1, Node n2) {
this.add(n1);
this.add(n2);
}
}
static class Triangle extends ArrayList<Node> {
private Node mCentre;
private double mRad;
// private static final Logger logger =
// LoggerFactory.getLogger("container.Triangle");
@Override
public boolean add(Node n) {
if (this.size() > 3) {
throw new IllegalStateException("Can't add more than three " + "Nodes to Triangle.");
}
super.add(n);
if (this.size() == 3) {
calculateCircle();
// logger.debug("This triangle has " + mCentre.getLat() + " " +
// mCentre.getLng() +<SUF>
}
return true;
}
@Override
public Node get(int index) {
if (index > 3) {
throw new IllegalStateException("A triangle has only three points");
}
return super.get(index);
}
public boolean isEncompassing(Node n) {
// logger.debug("Values for isEncompassing: "+n.naiveDist(mCentre)+" "+mRad
// );
return n.naiveDist(mCentre) <= mRad;
}
private void calculateCircle() {
mCentre = new Node(0, 0);
double x1 = this.get(0).getLng();
double y1 = this.get(0).getLat();
double x2 = this.get(1).getLng();
double y2 = this.get(1).getLat();
double x3 = this.get(2).getLng();
double y3 = this.get(2).getLat();
double dy21 = y2 - y1;
double dy32 = y3 - y2;
// logger.debug("Values: " + x1 + " " + y1 + " " + x2 + " " + y2 +
// " " + x3 + " " + y3 );
// Checking for edge cases
// Mostly to prevent division by zero
if (isZero(dy21) && isZero(dy32)) {
// All three are on the same horizontal line
if (x2 > x1) {
if (x3 > x2) {
x2 = x3;
}
} else if (x3 < x1) {
x1 = x3;
}
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(y1);
// logger.debug("branch 1");
} else if (isZero(dy21)) {
// Node1 and Node2 are on the same horizontal line
// logger.debug("branch 2: " + dy21 + " " +dy32);
double m1 = -(x3 - x2) / dy32;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((x1 + x2) / 2);
mCentre.setLat(m1 * (mCentre.getLng() - mx1) + my1);
// logger.debug("branch 2: " + mCentre.getLat() + " " +
// mCentre.getLng());
} else if (isZero(dy32)) {
// Node2 and Node3 are on the same horizontal line
double m0 = -(x2 - x1) / dy21;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
mCentre.setLng((x2 + x3) / 2);
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 3");
// Common case. No Nodes are on the same horizontal line
} else {
double m0 = -(x2 - x1) / dy21;
double m1 = -(x3 - x2) / dy32;
double mx0 = (x1 + x2) / 2;
double my0 = (y1 + y2) / 2;
double mx1 = (x2 + x3) / 2;
double my1 = (y2 + y3) / 2;
mCentre.setLng((m0 * mx0 - m1 * mx1 + my1 - my0) / (m0 - m1));
mCentre.setLat(m0 * (mCentre.getLng() - mx0) + my0);
// logger.debug("branch 4");
}
// Calculating circle's radius
double rx = x3 - mCentre.getLng();
double ry = y3 - mCentre.getLat();
double r2 = rx * rx + ry * ry;
mRad = Math.sqrt(r2);
// make the radius slightly bigger
mRad = mRad + 2 * Node.EPSILON;
}
private boolean isZero(double d) {
return Math.abs(d) < Node.EPSILON;
}
public boolean isLeftOf(Node n) {
return n.getLng() > (mCentre.getLng() + mRad);
}
}
}
|
209708_18 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| rrr6399/JSatTrakLib | src/name/gano/astro/Atmosphere.java | 3,492 | // Height, density parameters
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density<SUF>
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209708_20 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| rrr6399/JSatTrakLib | src/name/gano/astro/Atmosphere.java | 3,492 | // Satellite height (in km)
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height<SUF>
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209708_30 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| rrr6399/JSatTrakLib | src/name/gano/astro/Atmosphere.java | 3,492 | // loop over N_Coef height regimes
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over<SUF>
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209715_18 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| mdmzero0/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,510 | // Height, density parameters
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density<SUF>
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209715_20 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| mdmzero0/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,510 | // Satellite height (in km)
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height<SUF>
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209715_30 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| mdmzero0/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,510 | // loop over N_Coef height regimes
| line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* Copyright (C) 2009 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSatTrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over<SUF>
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
|
209717_10 | /*
* Emulator game server Aion 2.7 from the command of developers 'Aion-Knight Dev. Team' is
* free software; you can redistribute it and/or modify it under the terms of
* GNU affero general Public License (GNU GPL)as published by the free software
* security (FSF), or to License version 3 or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranties related to
* CONSUMER PROPERTIES and SUITABILITY FOR CERTAIN PURPOSES. For details, see
* General Public License is the GNU.
*
* You should have received a copy of the GNU affero general Public License along with this program.
* If it is not, write to the Free Software Foundation, Inc., 675 Mass Ave,
* Cambridge, MA 02139, USA
*
* Web developers : http://aion-knight.ru
* Support of the game client : Aion 2.7- 'Arena of Death' (Innova)
* The version of the server : Aion-Knight 2.7 (Beta version)
*/
package usercommands;
import gameserver.model.Race;
import gameserver.model.gameobjects.Item;
import gameserver.model.gameobjects.player.Player;
import gameserver.model.gameobjects.stats.StatEnum;
import gameserver.model.group.PlayerGroup;
import gameserver.model.legion.Legion;
import gameserver.network.aion.serverpackets.SM_QUESTIONNAIRE;
import gameserver.utils.PacketSendUtility;
import gameserver.utils.Util;
import gameserver.utils.chathandlers.UserCommand;
import gameserver.utils.idfactory.IDFactory;
import gameserver.world.World;
import java.util.Iterator;
import java.util.List;
public class PlayerInfo extends UserCommand
{
public PlayerInfo() {
super("playerinfo");
}
@Override
public void executeCommand(Player player, String params)
{
String[] args = params.split(" ");
Player target = World.getInstance().findPlayer(Util.convertName(args[0]));
if (target == null) {
PacketSendUtility.sendMessage(player, "The player with this name is not on a network or do not exist.");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("<poll>\n");
sb.append("<poll_introduction>\n");
sb.append(" <![CDATA[<font color='4CB1E5'>Player Info - Aion-Knight Dev.</font>]]>\n");
sb.append("</poll_introduction>\n");
sb.append("<poll_title>\n");
sb.append(" <font color='ffc519'></font>\n");
sb.append("</poll_title>\n");
sb.append("<start_date></start_date>\n");
sb.append("<end_date></end_date>\n");
sb.append("<servers></servers>\n");
sb.append("<order_num></order_num>\n");
sb.append("<race></race>\n");
sb.append("<main_class></main_class>\n");
sb.append("<world_id></world_id>\n");
sb.append("<item_id></item_id>\n");
sb.append("<item_cnt></item_cnt>\n");
sb.append("<level>1~55</level>\n");
sb.append("<questions>\n");
sb.append(" <question>\n");
sb.append(" <title>\n");
sb.append(" <![CDATA[\n");
sb.append("<br><br>\n");
if (target.getCommonData().getRace() == Race.ELYOS)
{
sb.append("Information about the player " + target.getName() + ": <img src='http://www.aion-destination.de/_images/elyos.png'><br><hr><br><br>\n");
}
else
{
sb.append("Information about the player " + target.getName() + ": <img src='http://sites.google.com/site/aioninfos/bilder/sonstiges/Asmodier-Symbol-35x40.png'><br><hr><br><br>\n");
}
//Falls sie die selbe Rasse haben bzw. es ein GM ist, wird der HP/MP/DP Status in % ausgegeben
if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0)
{
int hpinPercent = target.getLifeStats().getCurrentHp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXHP);
int mpinPercent = target.getLifeStats().getCurrentMp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXMP);
int dpinPercent = target.getCommonData().getDp()*100/4000;
//Gesundheit grafisch darstellen
sb.append("Gesundheit: [<font color ='00FF00'>");
int i = 1;
for (i = 1; i < hpinPercent/5; i++)
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
int k = 20-i;
for (i = 1; i < k; i++)
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + hpinPercent + "%) (" + target.getLifeStats().getCurrentHp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXHP) + " TP)<br>");
if (hpinPercent == 0) //Falls der Spieler keine Gesundheit mehr hat also tot ist sind alle Balken rot und es erscheint Tot neben dem Leben
{
sb.append(" <font color ='FF0000'>Tot</font>");
sb.append("<br>Mana: [<font color='FF0000'>|||||||||| ||||||||||</font>]");
sb.append("<br>Göttliche Kraft: [font color='FF0000'>|||||||||| ||||||||||</font>");
}
else //ansonsten werden Mana und G�ttliche Kraft berechnet
{
sb.append("<br>");
//Mana grafisch darstellen
sb.append("Mana: [<font color ='00FFFF'>");
for (i = 1; i < mpinPercent/5; i++) //gr�ne Gesundheitsbalken
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
k = 20-i;
for (i = 1; i < k; i++) //Rote Gesundheitsbalken
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + mpinPercent + "%) (" + target.getLifeStats().getCurrentMp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXMP) + " MP)<br>");
//G�ttliche Kraft grafisch darstellen
sb.append("Göttliche Kraft: [<font color='FFCC00'>");
for (i = 1; i < dpinPercent/5; i++)
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
k = 20-i;
for (i = 1; i < k; i++)
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + dpinPercent + "%) (" + target.getCommonData().getDp() + "/4000 GK)<br>");
}
}
sb.append("Level: " + target.getLevel() + "<br>\n");
//sb.append("Online: " + (System.currentTimeMillis() - target.getCommonData().getLastOnline().getTime()) / 60000 + " Minuten<br>\n");
if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0)
{
//PacketSendUtility.broadcastPacket(((Player) player), new SM_MESSAGE(((Player) player),"Position von [Pos:" + target.getName() + ";" + target.getPosition().getMapId() + " " + target.getPosition().getX() + " " + target.getPosition().getY() + " 0.0 -1]" , ChatType.NORMAL), true);
//TODO Post des Ortes via Chat... Umwandlung in Ortsbezogene Markierung??
}
sb.append("Klasse: ");
int targetclass = target.getPlayerClass().getClassId();
if (targetclass == 0) { sb.append("Krieger"); }
else if (targetclass == 1) { sb.append("Gladiator"); }
else if (targetclass == 2) { sb.append("Templer"); }
else if (targetclass == 3) { sb.append("Späher"); }
else if (targetclass == 4) { sb.append("Assassine"); }
else if (targetclass == 5) { sb.append("Jäger"); }
else if (targetclass == 6) { sb.append("Magier"); }
else if (targetclass == 7) { sb.append("Zauberer"); }
else if (targetclass == 8) { sb.append("Beschwörer"); }
else if (targetclass == 9) { sb.append("Priester"); }
else if (targetclass == 10) { sb.append("Kleriker"); }
else if (targetclass == 11) { sb.append("Kantor"); }
sb.append("<br>");
if (target.getCommonData().getRace() == Race.ELYOS)
{
sb.append("Rasse: Elyos<br>\n");
}
else
{
sb.append("Rasse: Asmodier<br>\n");
}
StringBuilder strbld = new StringBuilder("Gruppe: <br>--Leitung: \n");
PlayerGroup group = target.getPlayerGroup();
if (group == null)
sb.append("Gruppe: keine<br>\n");
else {
Iterator<Player> it = group.getMembers().iterator();
strbld.append(group.getGroupLeader().getName() + "<br>--Mitglieder:<br>\n");
while (it.hasNext()) {
Player act = (Player) it.next();
strbld.append("----" + act.getName() + "<br>\n");
}
sb.append(strbld.toString());
}
Legion legion = target.getLegion();
if (legion == null)
{
sb.append("Legion: keine<br>\n");
}
else
{
sb.append("Legion: " + legion.getLegionName() + "<br>\n");
}
if (player.getAccessLevel() > 0)
{
sb.append("<hr>");
sb.append("Zusätzliche Informationen für Teammitglieder:<br><br>");
sb.append("Account Name: " + target.getClientConnection().getAccount().getName() + "<br>\n");
//sb.append("IP: " + target.getClientConnection.getIP() + "<br>\n");
try {
if (args[1].equals("+items"))
{
sb.append("<br><hr><br>Item Informationen:<br><br>");
StringBuilder itstrbld = new StringBuilder("-- Inventar:<br>");
List<Item> items = target.getInventory().getAllItems();
Iterator<Item> it = items.iterator();
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>");
}
}
items.clear();
items = target.getEquipment().getEquippedItems();
it = items.iterator();
itstrbld.append("<br>-- Ausgerüstet:<br>");
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>");
}
}
items.clear();
items = target.getWarehouse().getAllItems();
it = items.iterator();
itstrbld.append("<br>-- Lagerhaus:<br>");
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]" + "<br>");
}
}
sb.append(itstrbld.toString());
}
} catch (Exception e) { }
}
else if (player.getAccessLevel() == 0 && args[1].equals("+items"))
{
sb.append("<br><hr><br>Du hast nicht genug Rechte, um Item Informationen abzurufen.<br><br>");
}
sb.append("<br><br><br>\n");
sb.append(" ]]>\n");
sb.append(" </title>\n");
sb.append(" <select>\n");
sb.append("<input type='radio'>");
sb.append("Danke für die Info!");
sb.append("</input>\n");
sb.append(" </select>\n");
sb.append(" </question>\n");
sb.append("</questions>\n");
sb.append("</poll>\n");
String html = sb.toString();
final int messageId = IDFactory.getInstance().nextId();
byte packet_count = (byte) Math.ceil(html.length() / (Short.MAX_VALUE - 8) + 1);
if (packet_count < 256) {
for (byte i = 0; i < packet_count; i++) {
try {
int from = i * (Short.MAX_VALUE - 8), to = (i + 1) * (Short.MAX_VALUE - 8);
if (from < 0)
from = 0;
if (to > html.length())
to = html.length();
String sub = html.substring(from, to);
player.getClientConnection().sendPacket(new SM_QUESTIONNAIRE(messageId, i, packet_count, sub));
}
catch (Exception e) {
}
}
}
}
} | shanecode/aionknight | gameserver/data/scripts/system/handlers/usercommands/PlayerInfo.java | 3,895 | //sb.append("IP: " + target.getClientConnection.getIP() + "<br>\n");
| line_comment | nl | /*
* Emulator game server Aion 2.7 from the command of developers 'Aion-Knight Dev. Team' is
* free software; you can redistribute it and/or modify it under the terms of
* GNU affero general Public License (GNU GPL)as published by the free software
* security (FSF), or to License version 3 or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranties related to
* CONSUMER PROPERTIES and SUITABILITY FOR CERTAIN PURPOSES. For details, see
* General Public License is the GNU.
*
* You should have received a copy of the GNU affero general Public License along with this program.
* If it is not, write to the Free Software Foundation, Inc., 675 Mass Ave,
* Cambridge, MA 02139, USA
*
* Web developers : http://aion-knight.ru
* Support of the game client : Aion 2.7- 'Arena of Death' (Innova)
* The version of the server : Aion-Knight 2.7 (Beta version)
*/
package usercommands;
import gameserver.model.Race;
import gameserver.model.gameobjects.Item;
import gameserver.model.gameobjects.player.Player;
import gameserver.model.gameobjects.stats.StatEnum;
import gameserver.model.group.PlayerGroup;
import gameserver.model.legion.Legion;
import gameserver.network.aion.serverpackets.SM_QUESTIONNAIRE;
import gameserver.utils.PacketSendUtility;
import gameserver.utils.Util;
import gameserver.utils.chathandlers.UserCommand;
import gameserver.utils.idfactory.IDFactory;
import gameserver.world.World;
import java.util.Iterator;
import java.util.List;
public class PlayerInfo extends UserCommand
{
public PlayerInfo() {
super("playerinfo");
}
@Override
public void executeCommand(Player player, String params)
{
String[] args = params.split(" ");
Player target = World.getInstance().findPlayer(Util.convertName(args[0]));
if (target == null) {
PacketSendUtility.sendMessage(player, "The player with this name is not on a network or do not exist.");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("<poll>\n");
sb.append("<poll_introduction>\n");
sb.append(" <![CDATA[<font color='4CB1E5'>Player Info - Aion-Knight Dev.</font>]]>\n");
sb.append("</poll_introduction>\n");
sb.append("<poll_title>\n");
sb.append(" <font color='ffc519'></font>\n");
sb.append("</poll_title>\n");
sb.append("<start_date></start_date>\n");
sb.append("<end_date></end_date>\n");
sb.append("<servers></servers>\n");
sb.append("<order_num></order_num>\n");
sb.append("<race></race>\n");
sb.append("<main_class></main_class>\n");
sb.append("<world_id></world_id>\n");
sb.append("<item_id></item_id>\n");
sb.append("<item_cnt></item_cnt>\n");
sb.append("<level>1~55</level>\n");
sb.append("<questions>\n");
sb.append(" <question>\n");
sb.append(" <title>\n");
sb.append(" <![CDATA[\n");
sb.append("<br><br>\n");
if (target.getCommonData().getRace() == Race.ELYOS)
{
sb.append("Information about the player " + target.getName() + ": <img src='http://www.aion-destination.de/_images/elyos.png'><br><hr><br><br>\n");
}
else
{
sb.append("Information about the player " + target.getName() + ": <img src='http://sites.google.com/site/aioninfos/bilder/sonstiges/Asmodier-Symbol-35x40.png'><br><hr><br><br>\n");
}
//Falls sie die selbe Rasse haben bzw. es ein GM ist, wird der HP/MP/DP Status in % ausgegeben
if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0)
{
int hpinPercent = target.getLifeStats().getCurrentHp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXHP);
int mpinPercent = target.getLifeStats().getCurrentMp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXMP);
int dpinPercent = target.getCommonData().getDp()*100/4000;
//Gesundheit grafisch darstellen
sb.append("Gesundheit: [<font color ='00FF00'>");
int i = 1;
for (i = 1; i < hpinPercent/5; i++)
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
int k = 20-i;
for (i = 1; i < k; i++)
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + hpinPercent + "%) (" + target.getLifeStats().getCurrentHp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXHP) + " TP)<br>");
if (hpinPercent == 0) //Falls der Spieler keine Gesundheit mehr hat also tot ist sind alle Balken rot und es erscheint Tot neben dem Leben
{
sb.append(" <font color ='FF0000'>Tot</font>");
sb.append("<br>Mana: [<font color='FF0000'>|||||||||| ||||||||||</font>]");
sb.append("<br>Göttliche Kraft: [font color='FF0000'>|||||||||| ||||||||||</font>");
}
else //ansonsten werden Mana und G�ttliche Kraft berechnet
{
sb.append("<br>");
//Mana grafisch darstellen
sb.append("Mana: [<font color ='00FFFF'>");
for (i = 1; i < mpinPercent/5; i++) //gr�ne Gesundheitsbalken
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
k = 20-i;
for (i = 1; i < k; i++) //Rote Gesundheitsbalken
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + mpinPercent + "%) (" + target.getLifeStats().getCurrentMp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXMP) + " MP)<br>");
//G�ttliche Kraft grafisch darstellen
sb.append("Göttliche Kraft: [<font color='FFCC00'>");
for (i = 1; i < dpinPercent/5; i++)
{
sb.append("|");
if (i == 10)
{
sb.append(" ");
}
}
sb.append("</font><font color ='FF0000'>");
k = 20-i;
for (i = 1; i < k; i++)
{
sb.append("|");
if (20-k+i == 10)
{
sb.append(" ");
}
}
sb.append("</font>] (" + dpinPercent + "%) (" + target.getCommonData().getDp() + "/4000 GK)<br>");
}
}
sb.append("Level: " + target.getLevel() + "<br>\n");
//sb.append("Online: " + (System.currentTimeMillis() - target.getCommonData().getLastOnline().getTime()) / 60000 + " Minuten<br>\n");
if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0)
{
//PacketSendUtility.broadcastPacket(((Player) player), new SM_MESSAGE(((Player) player),"Position von [Pos:" + target.getName() + ";" + target.getPosition().getMapId() + " " + target.getPosition().getX() + " " + target.getPosition().getY() + " 0.0 -1]" , ChatType.NORMAL), true);
//TODO Post des Ortes via Chat... Umwandlung in Ortsbezogene Markierung??
}
sb.append("Klasse: ");
int targetclass = target.getPlayerClass().getClassId();
if (targetclass == 0) { sb.append("Krieger"); }
else if (targetclass == 1) { sb.append("Gladiator"); }
else if (targetclass == 2) { sb.append("Templer"); }
else if (targetclass == 3) { sb.append("Späher"); }
else if (targetclass == 4) { sb.append("Assassine"); }
else if (targetclass == 5) { sb.append("Jäger"); }
else if (targetclass == 6) { sb.append("Magier"); }
else if (targetclass == 7) { sb.append("Zauberer"); }
else if (targetclass == 8) { sb.append("Beschwörer"); }
else if (targetclass == 9) { sb.append("Priester"); }
else if (targetclass == 10) { sb.append("Kleriker"); }
else if (targetclass == 11) { sb.append("Kantor"); }
sb.append("<br>");
if (target.getCommonData().getRace() == Race.ELYOS)
{
sb.append("Rasse: Elyos<br>\n");
}
else
{
sb.append("Rasse: Asmodier<br>\n");
}
StringBuilder strbld = new StringBuilder("Gruppe: <br>--Leitung: \n");
PlayerGroup group = target.getPlayerGroup();
if (group == null)
sb.append("Gruppe: keine<br>\n");
else {
Iterator<Player> it = group.getMembers().iterator();
strbld.append(group.getGroupLeader().getName() + "<br>--Mitglieder:<br>\n");
while (it.hasNext()) {
Player act = (Player) it.next();
strbld.append("----" + act.getName() + "<br>\n");
}
sb.append(strbld.toString());
}
Legion legion = target.getLegion();
if (legion == null)
{
sb.append("Legion: keine<br>\n");
}
else
{
sb.append("Legion: " + legion.getLegionName() + "<br>\n");
}
if (player.getAccessLevel() > 0)
{
sb.append("<hr>");
sb.append("Zusätzliche Informationen für Teammitglieder:<br><br>");
sb.append("Account Name: " + target.getClientConnection().getAccount().getName() + "<br>\n");
//sb.append("IP: "<SUF>
try {
if (args[1].equals("+items"))
{
sb.append("<br><hr><br>Item Informationen:<br><br>");
StringBuilder itstrbld = new StringBuilder("-- Inventar:<br>");
List<Item> items = target.getInventory().getAllItems();
Iterator<Item> it = items.iterator();
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>");
}
}
items.clear();
items = target.getEquipment().getEquippedItems();
it = items.iterator();
itstrbld.append("<br>-- Ausgerüstet:<br>");
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>");
}
}
items.clear();
items = target.getWarehouse().getAllItems();
it = items.iterator();
itstrbld.append("<br>-- Lagerhaus:<br>");
if (items.isEmpty())
itstrbld.append("---- Keine");
else {
while (it.hasNext()) {
Item act = (Item) it.next();
itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]" + "<br>");
}
}
sb.append(itstrbld.toString());
}
} catch (Exception e) { }
}
else if (player.getAccessLevel() == 0 && args[1].equals("+items"))
{
sb.append("<br><hr><br>Du hast nicht genug Rechte, um Item Informationen abzurufen.<br><br>");
}
sb.append("<br><br><br>\n");
sb.append(" ]]>\n");
sb.append(" </title>\n");
sb.append(" <select>\n");
sb.append("<input type='radio'>");
sb.append("Danke für die Info!");
sb.append("</input>\n");
sb.append(" </select>\n");
sb.append(" </question>\n");
sb.append("</questions>\n");
sb.append("</poll>\n");
String html = sb.toString();
final int messageId = IDFactory.getInstance().nextId();
byte packet_count = (byte) Math.ceil(html.length() / (Short.MAX_VALUE - 8) + 1);
if (packet_count < 256) {
for (byte i = 0; i < packet_count; i++) {
try {
int from = i * (Short.MAX_VALUE - 8), to = (i + 1) * (Short.MAX_VALUE - 8);
if (from < 0)
from = 0;
if (to > html.length())
to = html.length();
String sub = html.substring(from, to);
player.getClientConnection().sendPacket(new SM_QUESTIONNAIRE(messageId, i, packet_count, sub));
}
catch (Exception e) {
}
}
}
}
} |
209726_42 | /* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cs.examples.propagation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractIntegrator;
import org.apache.commons.math3.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.forces.SphericalSpacecraft;
import org.orekit.forces.drag.Atmosphere;
import org.orekit.forces.drag.DragForce;
import org.orekit.forces.drag.HarrisPriester;
import org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel;
import org.orekit.forces.gravity.ThirdBodyAttraction;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.SolarRadiationPressure;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTCentralBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.PVCoordinates;
import fr.cs.examples.KeyValueFileParser;
/** Orekit tutorial for semi-analytical extrapolation using the DSST.
* <p>
* The parameters are read from the input file dsst-propagation.in located in the user's
* home directory (see commented example at src/tutorial/ressources/dsst-propagation.in).
* The results are written to the ouput file dsst-propagation.out in the same directory.
* </p>
* <p>
* Comparison between the DSST propagator and the numerical propagator can be optionally
* performed. Numerical results are written to the ouput file numerical-propagation.out.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
public class DSSTPropagation {
/** Program entry point.
* @param args program arguments
*/
public static void main(String[] args) {
try {
// configure Orekit data acces
Utils.setDataRoot("tutorial-orekit-data");
// input/output (in user's home directory)
File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in");
File output = new File(input.getParentFile(), "dsst-propagation.out");
new DSSTPropagation().run(input, output);
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
System.exit(1);
} catch (IllegalArgumentException iae) {
System.err.println(iae.getLocalizedMessage());
System.exit(1);
} catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
System.exit(1);
} catch (ParseException pe) {
System.err.println(pe.getLocalizedMessage());
System.exit(1);
}
}
/** Input parameter keys. */
private static enum ParameterKey {
ORBIT_DATE,
ORBIT_CIRCULAR_A,
ORBIT_CIRCULAR_EX,
ORBIT_CIRCULAR_EY,
ORBIT_CIRCULAR_I,
ORBIT_CIRCULAR_RAAN,
ORBIT_CIRCULAR_ALPHA,
ORBIT_EQUINOCTIAL_A,
ORBIT_EQUINOCTIAL_EX,
ORBIT_EQUINOCTIAL_EY,
ORBIT_EQUINOCTIAL_HX,
ORBIT_EQUINOCTIAL_HY,
ORBIT_EQUINOCTIAL_LAMBDA,
ORBIT_KEPLERIAN_A,
ORBIT_KEPLERIAN_E,
ORBIT_KEPLERIAN_I,
ORBIT_KEPLERIAN_PA,
ORBIT_KEPLERIAN_RAAN,
ORBIT_KEPLERIAN_ANOMALY,
ORBIT_ANGLE_TYPE,
ORBIT_CARTESIAN_PX,
ORBIT_CARTESIAN_PY,
ORBIT_CARTESIAN_PZ,
ORBIT_CARTESIAN_VX,
ORBIT_CARTESIAN_VY,
ORBIT_CARTESIAN_VZ,
ORBIT_IS_OSCULATING,
START_DATE,
DURATION,
DURATION_IN_DAYS,
OUTPUT_STEP,
FIXED_INTEGRATION_STEP,
NUMERICAL_COMPARISON,
CENTRAL_BODY_ORDER,
CENTRAL_BODY_DEGREE,
THIRD_BODY_MOON,
THIRD_BODY_SUN,
MASS,
DRAG,
DRAG_CD,
DRAG_SF,
SOLAR_RADIATION_PRESSURE,
SOLAR_RADIATION_PRESSURE_CR,
SOLAR_RADIATION_PRESSURE_SF;
}
private void run(final File input, final File output)
throws IOException, IllegalArgumentException, OrekitException, ParseException {
// read input parameters
KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
parser.parseInput(new FileInputStream(input));
// check mandatory input parameters
if (!parser.containsKey(ParameterKey.ORBIT_DATE)) {
throw new IOException("Orbit date is not defined.");
}
if (!parser.containsKey(ParameterKey.DURATION) && !parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
throw new IOException("Propagation duration is not defined.");
}
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = FastMath.min(degree, parser.getInt(ParameterKey.CENTRAL_BODY_ORDER));
// Potential coefficients providers
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(degree, order);
final NormalizedSphericalHarmonicsProvider normalized =
GravityFieldFactory.getConstantNormalizedProvider(degree, order);
// Central body attraction coefficient (m³/s²)
final double mu = unnormalized.getMu();
// Earth frame definition (for faster computation)
final Frame earthFrame = CelestialBodyFactory.getEarth().getBodyOrientedFrame();
// Orbit definition (inertial frame is EME2000)
final Orbit orbit = createOrbit(parser, FramesFactory.getEME2000(), utc, mu);
// DSST propagator definition
double mass = 1000.0;
if (parser.containsKey(ParameterKey.MASS)) {
mass = parser.getDouble(ParameterKey.MASS);
}
Boolean isOsculating = false;
if (parser.containsKey(ParameterKey.ORBIT_IS_OSCULATING)) {
isOsculating = parser.getBoolean(ParameterKey.ORBIT_IS_OSCULATING);
}
double fixedStepSize = -1.;
if (parser.containsKey(ParameterKey.FIXED_INTEGRATION_STEP)) {
fixedStepSize = parser.getDouble(ParameterKey.FIXED_INTEGRATION_STEP);
}
final DSSTPropagator dsstProp = createDSSTProp(orbit, mass, isOsculating, fixedStepSize);
// Set Force models
setForceModel(parser, unnormalized, earthFrame, dsstProp);
// Simulation properties
AbsoluteDate start;
if (parser.containsKey(ParameterKey.START_DATE)) {
start = parser.getDate(ParameterKey.START_DATE, utc);
} else {
start = parser.getDate(ParameterKey.ORBIT_DATE, utc);
}
double duration = 0.;
if (parser.containsKey(ParameterKey.DURATION)) {
duration = parser.getDouble(ParameterKey.DURATION);
}
if (parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
duration = parser.getDouble(ParameterKey.DURATION_IN_DAYS) * Constants.JULIAN_DAY;
}
double outStep = parser.getDouble(ParameterKey.OUTPUT_STEP);
// Add orbit handler
OrbitHandler dsstHandler = new OrbitHandler();
dsstProp.setMasterMode(outStep, dsstHandler);
// DSST Propagation
final double dsstOn = System.currentTimeMillis();
dsstProp.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time: " + (dsstOff - dsstOn) / 1000.);
// Print results
printOutput(output, dsstHandler, start);
System.out.println("DSST results saved as file " + output);
// Check if we want to compare numerical to DSST propagator (default is false)
if (parser.containsKey(ParameterKey.NUMERICAL_COMPARISON)
&& parser.getBoolean(ParameterKey.NUMERICAL_COMPARISON)) {
if ( !isOsculating ) {
System.out.println("\nWARNING:");
System.out.println("The DSST propagator considers a mean orbit while the numerical will consider an osculating one.");
System.out.println("The comparison will be meaningless.\n");
}
// output (in user's home directory)
File output_num = new File(input.getParentFile(), "numerical-propagation.out");
// Numerical propagator definition
final NumericalPropagator numProp = createNumProp(orbit, mass);
// Set Force models
setForceModel(parser, normalized, earthFrame, numProp);
// Add orbit handler
OrbitHandler numHandler = new OrbitHandler();
numProp.setMasterMode(outStep, numHandler);
// Numerical Propagation
final double numOn = System.currentTimeMillis();
numProp.propagate(start, start.shiftedBy(duration));
final double numOff = System.currentTimeMillis();
System.out.println("Numerical execution time: " + (numOff - numOn) / 1000.);
// Print results
printOutput(output_num, numHandler, start);
System.out.println("Numerical results saved as file " + output_num);
}
}
/** Create an orbit from input parameters
* @param parser input file parser
* @param frame inertial frame
* @param scale time scale
* @param mu central attraction coefficient
* @throws NoSuchElementException if input parameters are mising
* @throws IOException if input parameters are invalid
*/
private Orbit createOrbit(final KeyValueFileParser<ParameterKey> parser,
final Frame frame, final TimeScale scale, final double mu)
throws NoSuchElementException, IOException {
// Orbit definition
Orbit orbit;
PositionAngle angleType = PositionAngle.MEAN;
if (parser.containsKey(ParameterKey.ORBIT_ANGLE_TYPE)) {
angleType = PositionAngle.valueOf(parser.getString(ParameterKey.ORBIT_ANGLE_TYPE).toUpperCase());
}
if (parser.containsKey(ParameterKey.ORBIT_KEPLERIAN_A)) {
orbit = new KeplerianOrbit(parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_E),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_I),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_PA),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_RAAN),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_ANOMALY),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_EQUINOCTIAL_A)) {
orbit = new EquinoctialOrbit(parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EY),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HY),
parser.getAngle(ParameterKey.ORBIT_EQUINOCTIAL_LAMBDA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CIRCULAR_A)) {
orbit = new CircularOrbit(parser.getDouble(ParameterKey.ORBIT_CIRCULAR_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EX),
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EY),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_I),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_RAAN),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_ALPHA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CARTESIAN_PX)) {
final double[] pos = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PZ) * 1000.};
final double[] vel = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VZ) * 1000.};
orbit = new CartesianOrbit(new PVCoordinates(new Vector3D(pos), new Vector3D(vel)),
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else {
throw new IOException("Orbit definition is incomplete.");
}
return orbit;
}
/** Set up the DSST Propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @param isOsculating if orbital elements are osculating
* @param fixedStepSize step size for fixed step integrator (s)
* @throws OrekitException
*/
private DSSTPropagator createDSSTProp(final Orbit orbit,
final double mass,
final boolean isOsculating,
final double fixedStepSize) throws OrekitException {
AbstractIntegrator integrator;
if (fixedStepSize > 0.) {
integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
} else {
final double minStep = orbit.getKeplerianPeriod();
final double maxStep = minStep * 100.;
final double[][] tol = DSSTPropagator.tolerances(1.0, orbit);
integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
((AdaptiveStepsizeIntegrator) integrator).setInitialStepSize(10. * minStep);
}
DSSTPropagator dsstProp = new DSSTPropagator(integrator);
dsstProp.setInitialState(new SpacecraftState(orbit, mass), isOsculating);
return dsstProp;
}
/** Create the numerical propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @throws OrekitException
*/
private NumericalPropagator createNumProp(final Orbit orbit, final double mass) throws OrekitException {
final double[][] tol = NumericalPropagator.tolerances(1.0, orbit, orbit.getType());
final double minStep = 1.e-3;
final double maxStep = 1.e+3;
AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
integrator.setInitialStepSize(100.);
NumericalPropagator numProp = new NumericalPropagator(integrator);
numProp.setInitialState(new SpacecraftState(orbit, mass));
return numProp;
}
/** Set DSST propagator force models
*
* @param parser input file parser
* @param unnormalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param dsstProp DSST propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final UnnormalizedSphericalHarmonicsProvider unnormalized,
final Frame earthFrame,
final DSSTPropagator dsstProp) throws IOException, OrekitException {
final double ae = unnormalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body Force Model with un-normalized coefficients
dsstProp.addForceModel(new DSSTCentralBody(earthFrame, Constants.WGS84_EARTH_ANGULAR_VELOCITY, unnormalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
dsstProp.addForceModel(new DSSTAtmosphericDrag(atm,
parser.getDouble(ParameterKey.DRAG_CD),
parser.getDouble(ParameterKey.DRAG_SF)));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
dsstProp.addForceModel(new DSSTSolarRadiationPressure(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR),
parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
CelestialBodyFactory.getSun(), ae));
}
}
/** Set numerical propagator force models
*
* @param parser input file parser
* @param normalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param numProp numerical propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final NormalizedSphericalHarmonicsProvider normalized,
final Frame earthFrame,
final NumericalPropagator numProp) throws IOException, OrekitException {
final double ae = normalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body (normalized coefficients)
numProp.addForceModel(new HolmesFeatherstoneAttractionModel(earthFrame, normalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.DRAG_SF),
parser.getDouble(ParameterKey.DRAG_CD),
0., 0.);
numProp.addForceModel(new DragForce(atm, ssc));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
final double cR = parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR);
// cR being the DSST SRP coef and assuming a spherical spacecraft, the conversion is:
// cR = 1 + (1 - kA) * (1 - kR) * 4 / 9
// with kA arbitrary sets to 0
final double kR = 3.25 - 2.25 * cR;
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
0., 0., kR);
numProp.addForceModel(new SolarRadiationPressure(CelestialBodyFactory.getSun(), ae, ssc));
}
}
/** Print the results in the output file
*
* @param handler orbit handler
* @param output output file
* @param sart start date of propagation
* @throws OrekitException
* @throws IOException
*/
private void printOutput(final File output,
final OrbitHandler handler,
final AbsoluteDate start) throws OrekitException, IOException {
// Output format:
// time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
final String format = new String(" %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
buffer.write("## time_from_start(s) a(km) e i(deg) ");
buffer.write(" raan(deg) pa(deg) mean_anomaly(deg) ey/h ");
buffer.write(" ex/k hy/p hx/q mean_longitude_arg(deg)");
buffer.write(" Xposition(km) Yposition(km) Zposition(km) Xvelocity(km/s) ");
buffer.write(" Yvelocity(km/s) Zvelocity(km/s)");
buffer.newLine();
for (Orbit o : handler.getOrbits()) {
final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
// Time from start (s)
final double time = o.getDate().durationFrom(start);
// Semi-major axis (km)
final double a = o.getA() / 1000.;
// Keplerian elements
// Eccentricity
final double e = o.getE();
// Inclination (degrees)
final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
// Right Ascension of Ascending Node (degrees)
KeplerianOrbit ko = new KeplerianOrbit(o);
final double ra = Math.toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
// Perigee Argument (degrees)
final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
// Mean Anomaly (degrees)
final double am = Math.toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
// Equinoctial elements
// ey/h component of eccentricity vector
final double h = o.getEquinoctialEy();
// ex/k component of eccentricity vector
final double k = o.getEquinoctialEx();
// hy/p component of inclination vector
final double p = o.getHy();
// hx/q component of inclination vector
final double q = o.getHx();
// Mean Longitude Argument (degrees)
final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
// Cartesian elements
// Position along X in inertial frame (km)
final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
// Position along Y in inertial frame (km)
final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
// Position along Z in inertial frame (km)
final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
// Velocity along X in inertial frame (km/s)
final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
// Velocity along Y in inertial frame (km/s)
final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
// Velocity along Z in inertial frame (km/s)
final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
buffer.write(f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
buffer.newLine();
f.close();
}
buffer.close();
}
/** Specialized step handler catching the orbit at each step. */
private static class OrbitHandler implements OrekitFixedStepHandler {
/** List of orbits. */
private final List<Orbit> orbits;
private OrbitHandler() {
// initialise an empty list of orbit
orbits = new ArrayList<Orbit>();
}
/** {@inheritDoc} */
public void init(final SpacecraftState s0, final AbsoluteDate t) {
}
/** {@inheritDoc} */
public void handleStep(SpacecraftState currentState, boolean isLast) {
// fill in the list with the orbit from the current step
orbits.add(currentState.getOrbit());
}
/** Get the list of propagated orbits.
* @return orbits
*/
public List<Orbit> getOrbits() {
return orbits;
}
}
}
| treeform/orekit | src/tutorials/java/fr/cs/examples/propagation/DSSTPropagation.java | 7,519 | // Perigee Argument (degrees) | line_comment | nl | /* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cs.examples.propagation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractIntegrator;
import org.apache.commons.math3.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.forces.SphericalSpacecraft;
import org.orekit.forces.drag.Atmosphere;
import org.orekit.forces.drag.DragForce;
import org.orekit.forces.drag.HarrisPriester;
import org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel;
import org.orekit.forces.gravity.ThirdBodyAttraction;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.SolarRadiationPressure;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTCentralBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.PVCoordinates;
import fr.cs.examples.KeyValueFileParser;
/** Orekit tutorial for semi-analytical extrapolation using the DSST.
* <p>
* The parameters are read from the input file dsst-propagation.in located in the user's
* home directory (see commented example at src/tutorial/ressources/dsst-propagation.in).
* The results are written to the ouput file dsst-propagation.out in the same directory.
* </p>
* <p>
* Comparison between the DSST propagator and the numerical propagator can be optionally
* performed. Numerical results are written to the ouput file numerical-propagation.out.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
public class DSSTPropagation {
/** Program entry point.
* @param args program arguments
*/
public static void main(String[] args) {
try {
// configure Orekit data acces
Utils.setDataRoot("tutorial-orekit-data");
// input/output (in user's home directory)
File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in");
File output = new File(input.getParentFile(), "dsst-propagation.out");
new DSSTPropagation().run(input, output);
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
System.exit(1);
} catch (IllegalArgumentException iae) {
System.err.println(iae.getLocalizedMessage());
System.exit(1);
} catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
System.exit(1);
} catch (ParseException pe) {
System.err.println(pe.getLocalizedMessage());
System.exit(1);
}
}
/** Input parameter keys. */
private static enum ParameterKey {
ORBIT_DATE,
ORBIT_CIRCULAR_A,
ORBIT_CIRCULAR_EX,
ORBIT_CIRCULAR_EY,
ORBIT_CIRCULAR_I,
ORBIT_CIRCULAR_RAAN,
ORBIT_CIRCULAR_ALPHA,
ORBIT_EQUINOCTIAL_A,
ORBIT_EQUINOCTIAL_EX,
ORBIT_EQUINOCTIAL_EY,
ORBIT_EQUINOCTIAL_HX,
ORBIT_EQUINOCTIAL_HY,
ORBIT_EQUINOCTIAL_LAMBDA,
ORBIT_KEPLERIAN_A,
ORBIT_KEPLERIAN_E,
ORBIT_KEPLERIAN_I,
ORBIT_KEPLERIAN_PA,
ORBIT_KEPLERIAN_RAAN,
ORBIT_KEPLERIAN_ANOMALY,
ORBIT_ANGLE_TYPE,
ORBIT_CARTESIAN_PX,
ORBIT_CARTESIAN_PY,
ORBIT_CARTESIAN_PZ,
ORBIT_CARTESIAN_VX,
ORBIT_CARTESIAN_VY,
ORBIT_CARTESIAN_VZ,
ORBIT_IS_OSCULATING,
START_DATE,
DURATION,
DURATION_IN_DAYS,
OUTPUT_STEP,
FIXED_INTEGRATION_STEP,
NUMERICAL_COMPARISON,
CENTRAL_BODY_ORDER,
CENTRAL_BODY_DEGREE,
THIRD_BODY_MOON,
THIRD_BODY_SUN,
MASS,
DRAG,
DRAG_CD,
DRAG_SF,
SOLAR_RADIATION_PRESSURE,
SOLAR_RADIATION_PRESSURE_CR,
SOLAR_RADIATION_PRESSURE_SF;
}
private void run(final File input, final File output)
throws IOException, IllegalArgumentException, OrekitException, ParseException {
// read input parameters
KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
parser.parseInput(new FileInputStream(input));
// check mandatory input parameters
if (!parser.containsKey(ParameterKey.ORBIT_DATE)) {
throw new IOException("Orbit date is not defined.");
}
if (!parser.containsKey(ParameterKey.DURATION) && !parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
throw new IOException("Propagation duration is not defined.");
}
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = FastMath.min(degree, parser.getInt(ParameterKey.CENTRAL_BODY_ORDER));
// Potential coefficients providers
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(degree, order);
final NormalizedSphericalHarmonicsProvider normalized =
GravityFieldFactory.getConstantNormalizedProvider(degree, order);
// Central body attraction coefficient (m³/s²)
final double mu = unnormalized.getMu();
// Earth frame definition (for faster computation)
final Frame earthFrame = CelestialBodyFactory.getEarth().getBodyOrientedFrame();
// Orbit definition (inertial frame is EME2000)
final Orbit orbit = createOrbit(parser, FramesFactory.getEME2000(), utc, mu);
// DSST propagator definition
double mass = 1000.0;
if (parser.containsKey(ParameterKey.MASS)) {
mass = parser.getDouble(ParameterKey.MASS);
}
Boolean isOsculating = false;
if (parser.containsKey(ParameterKey.ORBIT_IS_OSCULATING)) {
isOsculating = parser.getBoolean(ParameterKey.ORBIT_IS_OSCULATING);
}
double fixedStepSize = -1.;
if (parser.containsKey(ParameterKey.FIXED_INTEGRATION_STEP)) {
fixedStepSize = parser.getDouble(ParameterKey.FIXED_INTEGRATION_STEP);
}
final DSSTPropagator dsstProp = createDSSTProp(orbit, mass, isOsculating, fixedStepSize);
// Set Force models
setForceModel(parser, unnormalized, earthFrame, dsstProp);
// Simulation properties
AbsoluteDate start;
if (parser.containsKey(ParameterKey.START_DATE)) {
start = parser.getDate(ParameterKey.START_DATE, utc);
} else {
start = parser.getDate(ParameterKey.ORBIT_DATE, utc);
}
double duration = 0.;
if (parser.containsKey(ParameterKey.DURATION)) {
duration = parser.getDouble(ParameterKey.DURATION);
}
if (parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
duration = parser.getDouble(ParameterKey.DURATION_IN_DAYS) * Constants.JULIAN_DAY;
}
double outStep = parser.getDouble(ParameterKey.OUTPUT_STEP);
// Add orbit handler
OrbitHandler dsstHandler = new OrbitHandler();
dsstProp.setMasterMode(outStep, dsstHandler);
// DSST Propagation
final double dsstOn = System.currentTimeMillis();
dsstProp.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time: " + (dsstOff - dsstOn) / 1000.);
// Print results
printOutput(output, dsstHandler, start);
System.out.println("DSST results saved as file " + output);
// Check if we want to compare numerical to DSST propagator (default is false)
if (parser.containsKey(ParameterKey.NUMERICAL_COMPARISON)
&& parser.getBoolean(ParameterKey.NUMERICAL_COMPARISON)) {
if ( !isOsculating ) {
System.out.println("\nWARNING:");
System.out.println("The DSST propagator considers a mean orbit while the numerical will consider an osculating one.");
System.out.println("The comparison will be meaningless.\n");
}
// output (in user's home directory)
File output_num = new File(input.getParentFile(), "numerical-propagation.out");
// Numerical propagator definition
final NumericalPropagator numProp = createNumProp(orbit, mass);
// Set Force models
setForceModel(parser, normalized, earthFrame, numProp);
// Add orbit handler
OrbitHandler numHandler = new OrbitHandler();
numProp.setMasterMode(outStep, numHandler);
// Numerical Propagation
final double numOn = System.currentTimeMillis();
numProp.propagate(start, start.shiftedBy(duration));
final double numOff = System.currentTimeMillis();
System.out.println("Numerical execution time: " + (numOff - numOn) / 1000.);
// Print results
printOutput(output_num, numHandler, start);
System.out.println("Numerical results saved as file " + output_num);
}
}
/** Create an orbit from input parameters
* @param parser input file parser
* @param frame inertial frame
* @param scale time scale
* @param mu central attraction coefficient
* @throws NoSuchElementException if input parameters are mising
* @throws IOException if input parameters are invalid
*/
private Orbit createOrbit(final KeyValueFileParser<ParameterKey> parser,
final Frame frame, final TimeScale scale, final double mu)
throws NoSuchElementException, IOException {
// Orbit definition
Orbit orbit;
PositionAngle angleType = PositionAngle.MEAN;
if (parser.containsKey(ParameterKey.ORBIT_ANGLE_TYPE)) {
angleType = PositionAngle.valueOf(parser.getString(ParameterKey.ORBIT_ANGLE_TYPE).toUpperCase());
}
if (parser.containsKey(ParameterKey.ORBIT_KEPLERIAN_A)) {
orbit = new KeplerianOrbit(parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_E),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_I),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_PA),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_RAAN),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_ANOMALY),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_EQUINOCTIAL_A)) {
orbit = new EquinoctialOrbit(parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EY),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HY),
parser.getAngle(ParameterKey.ORBIT_EQUINOCTIAL_LAMBDA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CIRCULAR_A)) {
orbit = new CircularOrbit(parser.getDouble(ParameterKey.ORBIT_CIRCULAR_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EX),
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EY),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_I),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_RAAN),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_ALPHA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CARTESIAN_PX)) {
final double[] pos = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PZ) * 1000.};
final double[] vel = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VZ) * 1000.};
orbit = new CartesianOrbit(new PVCoordinates(new Vector3D(pos), new Vector3D(vel)),
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else {
throw new IOException("Orbit definition is incomplete.");
}
return orbit;
}
/** Set up the DSST Propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @param isOsculating if orbital elements are osculating
* @param fixedStepSize step size for fixed step integrator (s)
* @throws OrekitException
*/
private DSSTPropagator createDSSTProp(final Orbit orbit,
final double mass,
final boolean isOsculating,
final double fixedStepSize) throws OrekitException {
AbstractIntegrator integrator;
if (fixedStepSize > 0.) {
integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
} else {
final double minStep = orbit.getKeplerianPeriod();
final double maxStep = minStep * 100.;
final double[][] tol = DSSTPropagator.tolerances(1.0, orbit);
integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
((AdaptiveStepsizeIntegrator) integrator).setInitialStepSize(10. * minStep);
}
DSSTPropagator dsstProp = new DSSTPropagator(integrator);
dsstProp.setInitialState(new SpacecraftState(orbit, mass), isOsculating);
return dsstProp;
}
/** Create the numerical propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @throws OrekitException
*/
private NumericalPropagator createNumProp(final Orbit orbit, final double mass) throws OrekitException {
final double[][] tol = NumericalPropagator.tolerances(1.0, orbit, orbit.getType());
final double minStep = 1.e-3;
final double maxStep = 1.e+3;
AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
integrator.setInitialStepSize(100.);
NumericalPropagator numProp = new NumericalPropagator(integrator);
numProp.setInitialState(new SpacecraftState(orbit, mass));
return numProp;
}
/** Set DSST propagator force models
*
* @param parser input file parser
* @param unnormalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param dsstProp DSST propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final UnnormalizedSphericalHarmonicsProvider unnormalized,
final Frame earthFrame,
final DSSTPropagator dsstProp) throws IOException, OrekitException {
final double ae = unnormalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body Force Model with un-normalized coefficients
dsstProp.addForceModel(new DSSTCentralBody(earthFrame, Constants.WGS84_EARTH_ANGULAR_VELOCITY, unnormalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
dsstProp.addForceModel(new DSSTAtmosphericDrag(atm,
parser.getDouble(ParameterKey.DRAG_CD),
parser.getDouble(ParameterKey.DRAG_SF)));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
dsstProp.addForceModel(new DSSTSolarRadiationPressure(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR),
parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
CelestialBodyFactory.getSun(), ae));
}
}
/** Set numerical propagator force models
*
* @param parser input file parser
* @param normalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param numProp numerical propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final NormalizedSphericalHarmonicsProvider normalized,
final Frame earthFrame,
final NumericalPropagator numProp) throws IOException, OrekitException {
final double ae = normalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body (normalized coefficients)
numProp.addForceModel(new HolmesFeatherstoneAttractionModel(earthFrame, normalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.DRAG_SF),
parser.getDouble(ParameterKey.DRAG_CD),
0., 0.);
numProp.addForceModel(new DragForce(atm, ssc));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
final double cR = parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR);
// cR being the DSST SRP coef and assuming a spherical spacecraft, the conversion is:
// cR = 1 + (1 - kA) * (1 - kR) * 4 / 9
// with kA arbitrary sets to 0
final double kR = 3.25 - 2.25 * cR;
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
0., 0., kR);
numProp.addForceModel(new SolarRadiationPressure(CelestialBodyFactory.getSun(), ae, ssc));
}
}
/** Print the results in the output file
*
* @param handler orbit handler
* @param output output file
* @param sart start date of propagation
* @throws OrekitException
* @throws IOException
*/
private void printOutput(final File output,
final OrbitHandler handler,
final AbsoluteDate start) throws OrekitException, IOException {
// Output format:
// time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
final String format = new String(" %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
buffer.write("## time_from_start(s) a(km) e i(deg) ");
buffer.write(" raan(deg) pa(deg) mean_anomaly(deg) ey/h ");
buffer.write(" ex/k hy/p hx/q mean_longitude_arg(deg)");
buffer.write(" Xposition(km) Yposition(km) Zposition(km) Xvelocity(km/s) ");
buffer.write(" Yvelocity(km/s) Zvelocity(km/s)");
buffer.newLine();
for (Orbit o : handler.getOrbits()) {
final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
// Time from start (s)
final double time = o.getDate().durationFrom(start);
// Semi-major axis (km)
final double a = o.getA() / 1000.;
// Keplerian elements
// Eccentricity
final double e = o.getE();
// Inclination (degrees)
final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
// Right Ascension of Ascending Node (degrees)
KeplerianOrbit ko = new KeplerianOrbit(o);
final double ra = Math.toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
// Perigee Argument<SUF>
final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
// Mean Anomaly (degrees)
final double am = Math.toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
// Equinoctial elements
// ey/h component of eccentricity vector
final double h = o.getEquinoctialEy();
// ex/k component of eccentricity vector
final double k = o.getEquinoctialEx();
// hy/p component of inclination vector
final double p = o.getHy();
// hx/q component of inclination vector
final double q = o.getHx();
// Mean Longitude Argument (degrees)
final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
// Cartesian elements
// Position along X in inertial frame (km)
final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
// Position along Y in inertial frame (km)
final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
// Position along Z in inertial frame (km)
final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
// Velocity along X in inertial frame (km/s)
final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
// Velocity along Y in inertial frame (km/s)
final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
// Velocity along Z in inertial frame (km/s)
final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
buffer.write(f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
buffer.newLine();
f.close();
}
buffer.close();
}
/** Specialized step handler catching the orbit at each step. */
private static class OrbitHandler implements OrekitFixedStepHandler {
/** List of orbits. */
private final List<Orbit> orbits;
private OrbitHandler() {
// initialise an empty list of orbit
orbits = new ArrayList<Orbit>();
}
/** {@inheritDoc} */
public void init(final SpacecraftState s0, final AbsoluteDate t) {
}
/** {@inheritDoc} */
public void handleStep(SpacecraftState currentState, boolean isLast) {
// fill in the list with the orbit from the current step
orbits.add(currentState.getOrbit());
}
/** Get the list of propagated orbits.
* @return orbits
*/
public List<Orbit> getOrbits() {
return orbits;
}
}
}
|
209729_42 | /* Copyright 2002-2015 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cs.examples.propagation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractIntegrator;
import org.apache.commons.math3.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.forces.SphericalSpacecraft;
import org.orekit.forces.drag.Atmosphere;
import org.orekit.forces.drag.DragForce;
import org.orekit.forces.drag.HarrisPriester;
import org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel;
import org.orekit.forces.gravity.ThirdBodyAttraction;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.SolarRadiationPressure;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTCentralBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.PVCoordinates;
import fr.cs.examples.KeyValueFileParser;
/** Orekit tutorial for semi-analytical extrapolation using the DSST.
* <p>
* The parameters are read from the input file dsst-propagation.in located in the user's
* home directory (see commented example at src/tutorial/ressources/dsst-propagation.in).
* The results are written to the ouput file dsst-propagation.out in the same directory.
* </p>
* <p>
* Comparison between the DSST propagator and the numerical propagator can be optionally
* performed. Numerical results are written to the ouput file numerical-propagation.out.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
public class DSSTPropagation {
/** Program entry point.
* @param args program arguments
*/
public static void main(String[] args) {
try {
// configure Orekit data acces
Utils.setDataRoot("tutorial-orekit-data");
// input/output (in user's home directory)
File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in");
File output = new File(input.getParentFile(), "dsst-propagation.out");
new DSSTPropagation().run(input, output);
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
System.exit(1);
} catch (IllegalArgumentException iae) {
System.err.println(iae.getLocalizedMessage());
System.exit(1);
} catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
System.exit(1);
} catch (ParseException pe) {
System.err.println(pe.getLocalizedMessage());
System.exit(1);
}
}
/** Input parameter keys. */
private static enum ParameterKey {
ORBIT_DATE,
ORBIT_CIRCULAR_A,
ORBIT_CIRCULAR_EX,
ORBIT_CIRCULAR_EY,
ORBIT_CIRCULAR_I,
ORBIT_CIRCULAR_RAAN,
ORBIT_CIRCULAR_ALPHA,
ORBIT_EQUINOCTIAL_A,
ORBIT_EQUINOCTIAL_EX,
ORBIT_EQUINOCTIAL_EY,
ORBIT_EQUINOCTIAL_HX,
ORBIT_EQUINOCTIAL_HY,
ORBIT_EQUINOCTIAL_LAMBDA,
ORBIT_KEPLERIAN_A,
ORBIT_KEPLERIAN_E,
ORBIT_KEPLERIAN_I,
ORBIT_KEPLERIAN_PA,
ORBIT_KEPLERIAN_RAAN,
ORBIT_KEPLERIAN_ANOMALY,
ORBIT_ANGLE_TYPE,
ORBIT_CARTESIAN_PX,
ORBIT_CARTESIAN_PY,
ORBIT_CARTESIAN_PZ,
ORBIT_CARTESIAN_VX,
ORBIT_CARTESIAN_VY,
ORBIT_CARTESIAN_VZ,
ORBIT_IS_OSCULATING,
START_DATE,
DURATION,
DURATION_IN_DAYS,
OUTPUT_STEP,
FIXED_INTEGRATION_STEP,
NUMERICAL_COMPARISON,
CENTRAL_BODY_ORDER,
CENTRAL_BODY_DEGREE,
THIRD_BODY_MOON,
THIRD_BODY_SUN,
MASS,
DRAG,
DRAG_CD,
DRAG_SF,
SOLAR_RADIATION_PRESSURE,
SOLAR_RADIATION_PRESSURE_CR,
SOLAR_RADIATION_PRESSURE_SF;
}
private void run(final File input, final File output)
throws IOException, IllegalArgumentException, OrekitException, ParseException {
// read input parameters
KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
parser.parseInput(new FileInputStream(input));
// check mandatory input parameters
if (!parser.containsKey(ParameterKey.ORBIT_DATE)) {
throw new IOException("Orbit date is not defined.");
}
if (!parser.containsKey(ParameterKey.DURATION) && !parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
throw new IOException("Propagation duration is not defined.");
}
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = FastMath.min(degree, parser.getInt(ParameterKey.CENTRAL_BODY_ORDER));
// Potential coefficients providers
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(degree, order);
final NormalizedSphericalHarmonicsProvider normalized =
GravityFieldFactory.getConstantNormalizedProvider(degree, order);
// Central body attraction coefficient (m³/s²)
final double mu = unnormalized.getMu();
// Earth frame definition (for faster computation)
final Frame earthFrame = CelestialBodyFactory.getEarth().getBodyOrientedFrame();
// Orbit definition (inertial frame is EME2000)
final Orbit orbit = createOrbit(parser, FramesFactory.getEME2000(), utc, mu);
// DSST propagator definition
double mass = 1000.0;
if (parser.containsKey(ParameterKey.MASS)) {
mass = parser.getDouble(ParameterKey.MASS);
}
Boolean isOsculating = false;
if (parser.containsKey(ParameterKey.ORBIT_IS_OSCULATING)) {
isOsculating = parser.getBoolean(ParameterKey.ORBIT_IS_OSCULATING);
}
double fixedStepSize = -1.;
if (parser.containsKey(ParameterKey.FIXED_INTEGRATION_STEP)) {
fixedStepSize = parser.getDouble(ParameterKey.FIXED_INTEGRATION_STEP);
}
final DSSTPropagator dsstProp = createDSSTProp(orbit, mass, isOsculating, fixedStepSize);
// Set Force models
setForceModel(parser, unnormalized, earthFrame, dsstProp);
// Simulation properties
AbsoluteDate start;
if (parser.containsKey(ParameterKey.START_DATE)) {
start = parser.getDate(ParameterKey.START_DATE, utc);
} else {
start = parser.getDate(ParameterKey.ORBIT_DATE, utc);
}
double duration = 0.;
if (parser.containsKey(ParameterKey.DURATION)) {
duration = parser.getDouble(ParameterKey.DURATION);
}
if (parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
duration = parser.getDouble(ParameterKey.DURATION_IN_DAYS) * Constants.JULIAN_DAY;
}
double outStep = parser.getDouble(ParameterKey.OUTPUT_STEP);
// Add orbit handler
OrbitHandler dsstHandler = new OrbitHandler();
dsstProp.setMasterMode(outStep, dsstHandler);
// DSST Propagation
final double dsstOn = System.currentTimeMillis();
dsstProp.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time: " + (dsstOff - dsstOn) / 1000.);
// Print results
printOutput(output, dsstHandler, start);
System.out.println("DSST results saved as file " + output);
// Check if we want to compare numerical to DSST propagator (default is false)
if (parser.containsKey(ParameterKey.NUMERICAL_COMPARISON)
&& parser.getBoolean(ParameterKey.NUMERICAL_COMPARISON)) {
if ( !isOsculating ) {
System.out.println("\nWARNING:");
System.out.println("The DSST propagator considers a mean orbit while the numerical will consider an osculating one.");
System.out.println("The comparison will be meaningless.\n");
}
// output (in user's home directory)
File output_num = new File(input.getParentFile(), "numerical-propagation.out");
// Numerical propagator definition
final NumericalPropagator numProp = createNumProp(orbit, mass);
// Set Force models
setForceModel(parser, normalized, earthFrame, numProp);
// Add orbit handler
OrbitHandler numHandler = new OrbitHandler();
numProp.setMasterMode(outStep, numHandler);
// Numerical Propagation
final double numOn = System.currentTimeMillis();
numProp.propagate(start, start.shiftedBy(duration));
final double numOff = System.currentTimeMillis();
System.out.println("Numerical execution time: " + (numOff - numOn) / 1000.);
// Print results
printOutput(output_num, numHandler, start);
System.out.println("Numerical results saved as file " + output_num);
}
}
/** Create an orbit from input parameters
* @param parser input file parser
* @param frame inertial frame
* @param scale time scale
* @param mu central attraction coefficient
* @throws NoSuchElementException if input parameters are mising
* @throws IOException if input parameters are invalid
*/
private Orbit createOrbit(final KeyValueFileParser<ParameterKey> parser,
final Frame frame, final TimeScale scale, final double mu)
throws NoSuchElementException, IOException {
// Orbit definition
Orbit orbit;
PositionAngle angleType = PositionAngle.MEAN;
if (parser.containsKey(ParameterKey.ORBIT_ANGLE_TYPE)) {
angleType = PositionAngle.valueOf(parser.getString(ParameterKey.ORBIT_ANGLE_TYPE).toUpperCase());
}
if (parser.containsKey(ParameterKey.ORBIT_KEPLERIAN_A)) {
orbit = new KeplerianOrbit(parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_E),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_I),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_PA),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_RAAN),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_ANOMALY),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_EQUINOCTIAL_A)) {
orbit = new EquinoctialOrbit(parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EY),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HY),
parser.getAngle(ParameterKey.ORBIT_EQUINOCTIAL_LAMBDA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CIRCULAR_A)) {
orbit = new CircularOrbit(parser.getDouble(ParameterKey.ORBIT_CIRCULAR_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EX),
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EY),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_I),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_RAAN),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_ALPHA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CARTESIAN_PX)) {
final double[] pos = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PZ) * 1000.};
final double[] vel = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VZ) * 1000.};
orbit = new CartesianOrbit(new PVCoordinates(new Vector3D(pos), new Vector3D(vel)),
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else {
throw new IOException("Orbit definition is incomplete.");
}
return orbit;
}
/** Set up the DSST Propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @param isOsculating if orbital elements are osculating
* @param fixedStepSize step size for fixed step integrator (s)
* @throws OrekitException
*/
private DSSTPropagator createDSSTProp(final Orbit orbit,
final double mass,
final boolean isOsculating,
final double fixedStepSize) throws OrekitException {
AbstractIntegrator integrator;
if (fixedStepSize > 0.) {
integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
} else {
final double minStep = orbit.getKeplerianPeriod();
final double maxStep = minStep * 100.;
final double[][] tol = DSSTPropagator.tolerances(1.0, orbit);
integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
((AdaptiveStepsizeIntegrator) integrator).setInitialStepSize(10. * minStep);
}
DSSTPropagator dsstProp = new DSSTPropagator(integrator);
dsstProp.setInitialState(new SpacecraftState(orbit, mass), isOsculating);
return dsstProp;
}
/** Create the numerical propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @throws OrekitException
*/
private NumericalPropagator createNumProp(final Orbit orbit, final double mass) throws OrekitException {
final double[][] tol = NumericalPropagator.tolerances(1.0, orbit, orbit.getType());
final double minStep = 1.e-3;
final double maxStep = 1.e+3;
AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
integrator.setInitialStepSize(100.);
NumericalPropagator numProp = new NumericalPropagator(integrator);
numProp.setInitialState(new SpacecraftState(orbit, mass));
return numProp;
}
/** Set DSST propagator force models
*
* @param parser input file parser
* @param unnormalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param dsstProp DSST propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final UnnormalizedSphericalHarmonicsProvider unnormalized,
final Frame earthFrame,
final DSSTPropagator dsstProp) throws IOException, OrekitException {
final double ae = unnormalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body Force Model with un-normalized coefficients
dsstProp.addForceModel(new DSSTCentralBody(earthFrame, Constants.WGS84_EARTH_ANGULAR_VELOCITY, unnormalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
dsstProp.addForceModel(new DSSTAtmosphericDrag(atm,
parser.getDouble(ParameterKey.DRAG_CD),
parser.getDouble(ParameterKey.DRAG_SF)));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
dsstProp.addForceModel(new DSSTSolarRadiationPressure(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR),
parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
CelestialBodyFactory.getSun(), ae));
}
}
/** Set numerical propagator force models
*
* @param parser input file parser
* @param normalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param numProp numerical propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final NormalizedSphericalHarmonicsProvider normalized,
final Frame earthFrame,
final NumericalPropagator numProp) throws IOException, OrekitException {
final double ae = normalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body (normalized coefficients)
numProp.addForceModel(new HolmesFeatherstoneAttractionModel(earthFrame, normalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.DRAG_SF),
parser.getDouble(ParameterKey.DRAG_CD),
0., 0.);
numProp.addForceModel(new DragForce(atm, ssc));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
final double cR = parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR);
// cR being the DSST SRP coef and assuming a spherical spacecraft, the conversion is:
// cR = 1 + (1 - kA) * (1 - kR) * 4 / 9
// with kA arbitrary sets to 0
final double kR = 3.25 - 2.25 * cR;
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
0., 0., kR);
numProp.addForceModel(new SolarRadiationPressure(CelestialBodyFactory.getSun(), ae, ssc));
}
}
/** Print the results in the output file
*
* @param handler orbit handler
* @param output output file
* @param sart start date of propagation
* @throws OrekitException
* @throws IOException
*/
private void printOutput(final File output,
final OrbitHandler handler,
final AbsoluteDate start) throws OrekitException, IOException {
// Output format:
// time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
final String format = new String(" %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
buffer.write("## time_from_start(s) a(km) e i(deg) ");
buffer.write(" raan(deg) pa(deg) mean_anomaly(deg) ey/h ");
buffer.write(" ex/k hy/p hx/q mean_longitude_arg(deg)");
buffer.write(" Xposition(km) Yposition(km) Zposition(km) Xvelocity(km/s) ");
buffer.write(" Yvelocity(km/s) Zvelocity(km/s)");
buffer.newLine();
for (Orbit o : handler.getOrbits()) {
final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
// Time from start (s)
final double time = o.getDate().durationFrom(start);
// Semi-major axis (km)
final double a = o.getA() / 1000.;
// Keplerian elements
// Eccentricity
final double e = o.getE();
// Inclination (degrees)
final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
// Right Ascension of Ascending Node (degrees)
KeplerianOrbit ko = new KeplerianOrbit(o);
final double ra = Math.toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
// Perigee Argument (degrees)
final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
// Mean Anomaly (degrees)
final double am = Math.toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
// Equinoctial elements
// ey/h component of eccentricity vector
final double h = o.getEquinoctialEy();
// ex/k component of eccentricity vector
final double k = o.getEquinoctialEx();
// hy/p component of inclination vector
final double p = o.getHy();
// hx/q component of inclination vector
final double q = o.getHx();
// Mean Longitude Argument (degrees)
final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
// Cartesian elements
// Position along X in inertial frame (km)
final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
// Position along Y in inertial frame (km)
final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
// Position along Z in inertial frame (km)
final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
// Velocity along X in inertial frame (km/s)
final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
// Velocity along Y in inertial frame (km/s)
final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
// Velocity along Z in inertial frame (km/s)
final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
buffer.write(f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
buffer.newLine();
f.close();
}
buffer.close();
}
/** Specialized step handler catching the orbit at each step. */
private static class OrbitHandler implements OrekitFixedStepHandler {
/** List of orbits. */
private final List<Orbit> orbits;
private OrbitHandler() {
// initialise an empty list of orbit
orbits = new ArrayList<Orbit>();
}
/** {@inheritDoc} */
public void init(final SpacecraftState s0, final AbsoluteDate t) {
}
/** {@inheritDoc} */
public void handleStep(SpacecraftState currentState, boolean isLast) {
// fill in the list with the orbit from the current step
orbits.add(currentState.getOrbit());
}
/** Get the list of propagated orbits.
* @return orbits
*/
public List<Orbit> getOrbits() {
return orbits;
}
}
}
| Yakushima/Orekit | src/tutorials/java/fr/cs/examples/propagation/DSSTPropagation.java | 7,519 | // Perigee Argument (degrees) | line_comment | nl | /* Copyright 2002-2015 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cs.examples.propagation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractIntegrator;
import org.apache.commons.math3.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.forces.SphericalSpacecraft;
import org.orekit.forces.drag.Atmosphere;
import org.orekit.forces.drag.DragForce;
import org.orekit.forces.drag.HarrisPriester;
import org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel;
import org.orekit.forces.gravity.ThirdBodyAttraction;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.SolarRadiationPressure;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTCentralBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.PVCoordinates;
import fr.cs.examples.KeyValueFileParser;
/** Orekit tutorial for semi-analytical extrapolation using the DSST.
* <p>
* The parameters are read from the input file dsst-propagation.in located in the user's
* home directory (see commented example at src/tutorial/ressources/dsst-propagation.in).
* The results are written to the ouput file dsst-propagation.out in the same directory.
* </p>
* <p>
* Comparison between the DSST propagator and the numerical propagator can be optionally
* performed. Numerical results are written to the ouput file numerical-propagation.out.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
public class DSSTPropagation {
/** Program entry point.
* @param args program arguments
*/
public static void main(String[] args) {
try {
// configure Orekit data acces
Utils.setDataRoot("tutorial-orekit-data");
// input/output (in user's home directory)
File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in");
File output = new File(input.getParentFile(), "dsst-propagation.out");
new DSSTPropagation().run(input, output);
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
System.exit(1);
} catch (IllegalArgumentException iae) {
System.err.println(iae.getLocalizedMessage());
System.exit(1);
} catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
System.exit(1);
} catch (ParseException pe) {
System.err.println(pe.getLocalizedMessage());
System.exit(1);
}
}
/** Input parameter keys. */
private static enum ParameterKey {
ORBIT_DATE,
ORBIT_CIRCULAR_A,
ORBIT_CIRCULAR_EX,
ORBIT_CIRCULAR_EY,
ORBIT_CIRCULAR_I,
ORBIT_CIRCULAR_RAAN,
ORBIT_CIRCULAR_ALPHA,
ORBIT_EQUINOCTIAL_A,
ORBIT_EQUINOCTIAL_EX,
ORBIT_EQUINOCTIAL_EY,
ORBIT_EQUINOCTIAL_HX,
ORBIT_EQUINOCTIAL_HY,
ORBIT_EQUINOCTIAL_LAMBDA,
ORBIT_KEPLERIAN_A,
ORBIT_KEPLERIAN_E,
ORBIT_KEPLERIAN_I,
ORBIT_KEPLERIAN_PA,
ORBIT_KEPLERIAN_RAAN,
ORBIT_KEPLERIAN_ANOMALY,
ORBIT_ANGLE_TYPE,
ORBIT_CARTESIAN_PX,
ORBIT_CARTESIAN_PY,
ORBIT_CARTESIAN_PZ,
ORBIT_CARTESIAN_VX,
ORBIT_CARTESIAN_VY,
ORBIT_CARTESIAN_VZ,
ORBIT_IS_OSCULATING,
START_DATE,
DURATION,
DURATION_IN_DAYS,
OUTPUT_STEP,
FIXED_INTEGRATION_STEP,
NUMERICAL_COMPARISON,
CENTRAL_BODY_ORDER,
CENTRAL_BODY_DEGREE,
THIRD_BODY_MOON,
THIRD_BODY_SUN,
MASS,
DRAG,
DRAG_CD,
DRAG_SF,
SOLAR_RADIATION_PRESSURE,
SOLAR_RADIATION_PRESSURE_CR,
SOLAR_RADIATION_PRESSURE_SF;
}
private void run(final File input, final File output)
throws IOException, IllegalArgumentException, OrekitException, ParseException {
// read input parameters
KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
parser.parseInput(new FileInputStream(input));
// check mandatory input parameters
if (!parser.containsKey(ParameterKey.ORBIT_DATE)) {
throw new IOException("Orbit date is not defined.");
}
if (!parser.containsKey(ParameterKey.DURATION) && !parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
throw new IOException("Propagation duration is not defined.");
}
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = FastMath.min(degree, parser.getInt(ParameterKey.CENTRAL_BODY_ORDER));
// Potential coefficients providers
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(degree, order);
final NormalizedSphericalHarmonicsProvider normalized =
GravityFieldFactory.getConstantNormalizedProvider(degree, order);
// Central body attraction coefficient (m³/s²)
final double mu = unnormalized.getMu();
// Earth frame definition (for faster computation)
final Frame earthFrame = CelestialBodyFactory.getEarth().getBodyOrientedFrame();
// Orbit definition (inertial frame is EME2000)
final Orbit orbit = createOrbit(parser, FramesFactory.getEME2000(), utc, mu);
// DSST propagator definition
double mass = 1000.0;
if (parser.containsKey(ParameterKey.MASS)) {
mass = parser.getDouble(ParameterKey.MASS);
}
Boolean isOsculating = false;
if (parser.containsKey(ParameterKey.ORBIT_IS_OSCULATING)) {
isOsculating = parser.getBoolean(ParameterKey.ORBIT_IS_OSCULATING);
}
double fixedStepSize = -1.;
if (parser.containsKey(ParameterKey.FIXED_INTEGRATION_STEP)) {
fixedStepSize = parser.getDouble(ParameterKey.FIXED_INTEGRATION_STEP);
}
final DSSTPropagator dsstProp = createDSSTProp(orbit, mass, isOsculating, fixedStepSize);
// Set Force models
setForceModel(parser, unnormalized, earthFrame, dsstProp);
// Simulation properties
AbsoluteDate start;
if (parser.containsKey(ParameterKey.START_DATE)) {
start = parser.getDate(ParameterKey.START_DATE, utc);
} else {
start = parser.getDate(ParameterKey.ORBIT_DATE, utc);
}
double duration = 0.;
if (parser.containsKey(ParameterKey.DURATION)) {
duration = parser.getDouble(ParameterKey.DURATION);
}
if (parser.containsKey(ParameterKey.DURATION_IN_DAYS)) {
duration = parser.getDouble(ParameterKey.DURATION_IN_DAYS) * Constants.JULIAN_DAY;
}
double outStep = parser.getDouble(ParameterKey.OUTPUT_STEP);
// Add orbit handler
OrbitHandler dsstHandler = new OrbitHandler();
dsstProp.setMasterMode(outStep, dsstHandler);
// DSST Propagation
final double dsstOn = System.currentTimeMillis();
dsstProp.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time: " + (dsstOff - dsstOn) / 1000.);
// Print results
printOutput(output, dsstHandler, start);
System.out.println("DSST results saved as file " + output);
// Check if we want to compare numerical to DSST propagator (default is false)
if (parser.containsKey(ParameterKey.NUMERICAL_COMPARISON)
&& parser.getBoolean(ParameterKey.NUMERICAL_COMPARISON)) {
if ( !isOsculating ) {
System.out.println("\nWARNING:");
System.out.println("The DSST propagator considers a mean orbit while the numerical will consider an osculating one.");
System.out.println("The comparison will be meaningless.\n");
}
// output (in user's home directory)
File output_num = new File(input.getParentFile(), "numerical-propagation.out");
// Numerical propagator definition
final NumericalPropagator numProp = createNumProp(orbit, mass);
// Set Force models
setForceModel(parser, normalized, earthFrame, numProp);
// Add orbit handler
OrbitHandler numHandler = new OrbitHandler();
numProp.setMasterMode(outStep, numHandler);
// Numerical Propagation
final double numOn = System.currentTimeMillis();
numProp.propagate(start, start.shiftedBy(duration));
final double numOff = System.currentTimeMillis();
System.out.println("Numerical execution time: " + (numOff - numOn) / 1000.);
// Print results
printOutput(output_num, numHandler, start);
System.out.println("Numerical results saved as file " + output_num);
}
}
/** Create an orbit from input parameters
* @param parser input file parser
* @param frame inertial frame
* @param scale time scale
* @param mu central attraction coefficient
* @throws NoSuchElementException if input parameters are mising
* @throws IOException if input parameters are invalid
*/
private Orbit createOrbit(final KeyValueFileParser<ParameterKey> parser,
final Frame frame, final TimeScale scale, final double mu)
throws NoSuchElementException, IOException {
// Orbit definition
Orbit orbit;
PositionAngle angleType = PositionAngle.MEAN;
if (parser.containsKey(ParameterKey.ORBIT_ANGLE_TYPE)) {
angleType = PositionAngle.valueOf(parser.getString(ParameterKey.ORBIT_ANGLE_TYPE).toUpperCase());
}
if (parser.containsKey(ParameterKey.ORBIT_KEPLERIAN_A)) {
orbit = new KeplerianOrbit(parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_KEPLERIAN_E),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_I),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_PA),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_RAAN),
parser.getAngle(ParameterKey.ORBIT_KEPLERIAN_ANOMALY),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_EQUINOCTIAL_A)) {
orbit = new EquinoctialOrbit(parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_EY),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HX),
parser.getDouble(ParameterKey.ORBIT_EQUINOCTIAL_HY),
parser.getAngle(ParameterKey.ORBIT_EQUINOCTIAL_LAMBDA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CIRCULAR_A)) {
orbit = new CircularOrbit(parser.getDouble(ParameterKey.ORBIT_CIRCULAR_A) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EX),
parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EY),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_I),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_RAAN),
parser.getAngle(ParameterKey.ORBIT_CIRCULAR_ALPHA),
angleType,
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else if (parser.containsKey(ParameterKey.ORBIT_CARTESIAN_PX)) {
final double[] pos = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_PZ) * 1000.};
final double[] vel = {parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VX) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VY) * 1000.,
parser.getDouble(ParameterKey.ORBIT_CARTESIAN_VZ) * 1000.};
orbit = new CartesianOrbit(new PVCoordinates(new Vector3D(pos), new Vector3D(vel)),
frame,
parser.getDate(ParameterKey.ORBIT_DATE, scale),
mu
);
} else {
throw new IOException("Orbit definition is incomplete.");
}
return orbit;
}
/** Set up the DSST Propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @param isOsculating if orbital elements are osculating
* @param fixedStepSize step size for fixed step integrator (s)
* @throws OrekitException
*/
private DSSTPropagator createDSSTProp(final Orbit orbit,
final double mass,
final boolean isOsculating,
final double fixedStepSize) throws OrekitException {
AbstractIntegrator integrator;
if (fixedStepSize > 0.) {
integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
} else {
final double minStep = orbit.getKeplerianPeriod();
final double maxStep = minStep * 100.;
final double[][] tol = DSSTPropagator.tolerances(1.0, orbit);
integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
((AdaptiveStepsizeIntegrator) integrator).setInitialStepSize(10. * minStep);
}
DSSTPropagator dsstProp = new DSSTPropagator(integrator);
dsstProp.setInitialState(new SpacecraftState(orbit, mass), isOsculating);
return dsstProp;
}
/** Create the numerical propagator
*
* @param orbit initial orbit
* @param mass S/C mass (kg)
* @throws OrekitException
*/
private NumericalPropagator createNumProp(final Orbit orbit, final double mass) throws OrekitException {
final double[][] tol = NumericalPropagator.tolerances(1.0, orbit, orbit.getType());
final double minStep = 1.e-3;
final double maxStep = 1.e+3;
AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);
integrator.setInitialStepSize(100.);
NumericalPropagator numProp = new NumericalPropagator(integrator);
numProp.setInitialState(new SpacecraftState(orbit, mass));
return numProp;
}
/** Set DSST propagator force models
*
* @param parser input file parser
* @param unnormalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param dsstProp DSST propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final UnnormalizedSphericalHarmonicsProvider unnormalized,
final Frame earthFrame,
final DSSTPropagator dsstProp) throws IOException, OrekitException {
final double ae = unnormalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body Force Model with un-normalized coefficients
dsstProp.addForceModel(new DSSTCentralBody(earthFrame, Constants.WGS84_EARTH_ANGULAR_VELOCITY, unnormalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
dsstProp.addForceModel(new DSSTThirdBody(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
dsstProp.addForceModel(new DSSTAtmosphericDrag(atm,
parser.getDouble(ParameterKey.DRAG_CD),
parser.getDouble(ParameterKey.DRAG_SF)));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
dsstProp.addForceModel(new DSSTSolarRadiationPressure(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR),
parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
CelestialBodyFactory.getSun(), ae));
}
}
/** Set numerical propagator force models
*
* @param parser input file parser
* @param normalized spherical harmonics provider
* @param earthFrame Earth rotating frame
* @param numProp numerical propagator
* @throws IOException
* @throws OrekitException
*/
private void setForceModel(final KeyValueFileParser<ParameterKey> parser,
final NormalizedSphericalHarmonicsProvider normalized,
final Frame earthFrame,
final NumericalPropagator numProp) throws IOException, OrekitException {
final double ae = normalized.getAe();
final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE);
final int order = parser.getInt(ParameterKey.CENTRAL_BODY_ORDER);
if (order > degree) {
throw new IOException("Potential order cannot be higher than potential degree");
}
// Central Body (normalized coefficients)
numProp.addForceModel(new HolmesFeatherstoneAttractionModel(earthFrame, normalized));
// 3rd body (SUN)
if (parser.containsKey(ParameterKey.THIRD_BODY_SUN) && parser.getBoolean(ParameterKey.THIRD_BODY_SUN)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getSun()));
}
// 3rd body (MOON)
if (parser.containsKey(ParameterKey.THIRD_BODY_MOON) && parser.getBoolean(ParameterKey.THIRD_BODY_MOON)) {
numProp.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getMoon()));
}
// Drag
if (parser.containsKey(ParameterKey.DRAG) && parser.getBoolean(ParameterKey.DRAG)) {
final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame);
final Atmosphere atm = new HarrisPriester(CelestialBodyFactory.getSun(), earth, 6);
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.DRAG_SF),
parser.getDouble(ParameterKey.DRAG_CD),
0., 0.);
numProp.addForceModel(new DragForce(atm, ssc));
}
// Solar Radiation Pressure
if (parser.containsKey(ParameterKey.SOLAR_RADIATION_PRESSURE) && parser.getBoolean(ParameterKey.SOLAR_RADIATION_PRESSURE)) {
final double cR = parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_CR);
// cR being the DSST SRP coef and assuming a spherical spacecraft, the conversion is:
// cR = 1 + (1 - kA) * (1 - kR) * 4 / 9
// with kA arbitrary sets to 0
final double kR = 3.25 - 2.25 * cR;
final SphericalSpacecraft ssc = new SphericalSpacecraft(parser.getDouble(ParameterKey.SOLAR_RADIATION_PRESSURE_SF),
0., 0., kR);
numProp.addForceModel(new SolarRadiationPressure(CelestialBodyFactory.getSun(), ae, ssc));
}
}
/** Print the results in the output file
*
* @param handler orbit handler
* @param output output file
* @param sart start date of propagation
* @throws OrekitException
* @throws IOException
*/
private void printOutput(final File output,
final OrbitHandler handler,
final AbsoluteDate start) throws OrekitException, IOException {
// Output format:
// time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
final String format = new String(" %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
buffer.write("## time_from_start(s) a(km) e i(deg) ");
buffer.write(" raan(deg) pa(deg) mean_anomaly(deg) ey/h ");
buffer.write(" ex/k hy/p hx/q mean_longitude_arg(deg)");
buffer.write(" Xposition(km) Yposition(km) Zposition(km) Xvelocity(km/s) ");
buffer.write(" Yvelocity(km/s) Zvelocity(km/s)");
buffer.newLine();
for (Orbit o : handler.getOrbits()) {
final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
// Time from start (s)
final double time = o.getDate().durationFrom(start);
// Semi-major axis (km)
final double a = o.getA() / 1000.;
// Keplerian elements
// Eccentricity
final double e = o.getE();
// Inclination (degrees)
final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
// Right Ascension of Ascending Node (degrees)
KeplerianOrbit ko = new KeplerianOrbit(o);
final double ra = Math.toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
// Perigee Argument<SUF>
final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
// Mean Anomaly (degrees)
final double am = Math.toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
// Equinoctial elements
// ey/h component of eccentricity vector
final double h = o.getEquinoctialEy();
// ex/k component of eccentricity vector
final double k = o.getEquinoctialEx();
// hy/p component of inclination vector
final double p = o.getHy();
// hx/q component of inclination vector
final double q = o.getHx();
// Mean Longitude Argument (degrees)
final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
// Cartesian elements
// Position along X in inertial frame (km)
final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
// Position along Y in inertial frame (km)
final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
// Position along Z in inertial frame (km)
final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
// Velocity along X in inertial frame (km/s)
final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
// Velocity along Y in inertial frame (km/s)
final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
// Velocity along Z in inertial frame (km/s)
final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
buffer.write(f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
buffer.newLine();
f.close();
}
buffer.close();
}
/** Specialized step handler catching the orbit at each step. */
private static class OrbitHandler implements OrekitFixedStepHandler {
/** List of orbits. */
private final List<Orbit> orbits;
private OrbitHandler() {
// initialise an empty list of orbit
orbits = new ArrayList<Orbit>();
}
/** {@inheritDoc} */
public void init(final SpacecraftState s0, final AbsoluteDate t) {
}
/** {@inheritDoc} */
public void handleStep(SpacecraftState currentState, boolean isLast) {
// fill in the list with the orbit from the current step
orbits.add(currentState.getOrbit());
}
/** Get the list of propagated orbits.
* @return orbits
*/
public List<Orbit> getOrbits() {
return orbits;
}
}
}
|
209773_2 | package quickTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.hipparchus.ode.AbstractIntegrator;
import org.hipparchus.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.errors.OrekitException;
import org.orekit.forces.drag.DragSensitive;
import org.orekit.forces.drag.IsotropicDrag;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.IsotropicRadiationSingleCoefficient;
import org.orekit.forces.radiation.RadiationSensitive;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.models.earth.atmosphere.HarrisPriester;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.EphemerisGenerator;
import org.orekit.propagation.PropagationType;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTTesseral;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTZonal;
public class DSSTPropagation {
/** Private constructor for utility class. */
private DSSTPropagation() {
// empty
}
public static void main(final String[] args) {
try {
// configure Orekit
final File home = new File(System.getProperty("user.home"));
final File orekitData = new File(home, "orekit-data");
if (!orekitData.exists()) {
System.err.format(Locale.US, "Failed to find %s folder%n",
orekitData.getAbsolutePath());
System.err.format(Locale.US, "You need to download %s from %s, unzip it in %s and rename it 'orekit-data' for this tutorial to work%n",
"orekit-data-master.zip", "https://gitlab.orekit.org/orekit/orekit-data/-/archive/master/orekit-data-master.zip",
home.getAbsolutePath());
System.exit(1);
}
final DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();
manager.addProvider(new DirectoryCrawler(orekitData));
// gravitation coefficient
final double mu = 3.986004415e+14;
// inertial frame
final Frame inertialFrame = FramesFactory.getEME2000();
// Load Celestial bodies
// ---------------------
final CelestialBody sun = CelestialBodyFactory.getSun();
// Initial date
final AbsoluteDate initialDate = new AbsoluteDate(2024,07,02,12,0,0,TimeScalesFactory.getUTC());
// Initial orbit
final double RE = Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS;
final double a = 6878.e3; // semi major axis in meters
final double ecc = 2.e-2; // eccentricity
final double i = 97.4009688*Math.PI/180; // inclination
final double omega =Math.PI/2; // perigee argument
final double raan = 0; // right ascention of ascending node
final double lM = 0; // mean anomaly
final Orbit initialOrbit = new KeplerianOrbit(a, ecc, i, omega, raan, lM, PositionAngle.MEAN,
inertialFrame, initialDate, mu);
final double fixedStepSize = 2*Math.PI*Math.sqrt((a*a*a)/mu);
final int datastep = 100; // Interval between recorded data points on output file
final int duration = 500*86400;// in seconds
final double mass= 2.66;
final AbsoluteDate start = initialOrbit.getDate();
int output_step = 8600;
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final double rotationRate = Constants.WGS84_EARTH_ANGULAR_VELOCITY;
// Defining the Propagator
final AbstractIntegrator integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
final PropagationType outputType = PropagationType.MEAN;
final DSSTPropagator propagator = new DSSTPropagator(integrator, outputType);
propagator.setInitialState(new SpacecraftState(initialOrbit, mass), PropagationType.MEAN);
//Models
final IERSConventions conventions = IERSConventions.IERS_2010;
final Frame earthFrame = FramesFactory.getITRF(conventions, false);
final OneAxisEllipsoid earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
Constants.WGS84_EARTH_FLATTENING,
earthFrame);
// Gravity Field Force Model
final int ZonalMaxDegree = 15;
final int ZonalMaxOrder = 15;
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(ZonalMaxDegree, ZonalMaxOrder);
propagator.addForceModel(new DSSTZonal(unnormalized));
propagator.addForceModel(new DSSTTesseral(earthFrame, rotationRate, unnormalized));
// Atmosphere
final HarrisPriester atmos = new HarrisPriester(sun,earth);
// Drag
double crossArea = 0.025;
double Cd = 2.2;
DragSensitive ssc = new IsotropicDrag(crossArea, Cd);
propagator.addForceModel(new DSSTAtmosphericDrag(atmos, ssc, mu));
// Solar Radiation Pressure
double cR = 1.8;
double srpArea = 0.025;
final RadiationSensitive ssrc = new IsotropicRadiationSingleCoefficient(srpArea, cR);
propagator.addForceModel(new DSSTSolarRadiationPressure(sun, RE, ssrc, mu));
//Propagation
final EphemerisGenerator dsstGenerator = propagator.getEphemerisGenerator();
final double dsstOn = System.currentTimeMillis();
propagator.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time (without large file write) : " + (dsstOff - dsstOn) / 1000.);
final BoundedPropagator ephemeris = dsstGenerator.getGeneratedEphemeris();
System.out.format("%nEphemeris defined from %s to %s%n", ephemeris.getMinDate(), ephemeris.getMaxDate());
//Initialization of list of orbit ephemeris
ArrayList<KeplerianOrbit> orbitList = new ArrayList<>();
double interArgPer = 0;
List<Double> ArgPerList = new ArrayList<>();
//Writing the results to a text file
try {
FileWriter myWriter = new FileWriter("output/DSSTPropagation.txt");
//Writing Header
myWriter.write(" Semi-Major Axis ; Eccentricity ; Inclination ; Argument of the perigee ; Right Ascension of the Ascending node\n");
//Get values from ephemeris
for (int k = 0; k < duration/output_step; k= k + 1) {
AbsoluteDate intermediateDate = initialDate.shiftedBy(output_step*i);
SpacecraftState intermediateState = ephemeris.propagate(intermediateDate);
orbitList.add(new KeplerianOrbit(intermediateState.getOrbit()));
//Normalize Argument of the Perigee
if (orbitList.get(k).getRightAscensionOfAscendingNode() < - 2*Math.PI) {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode() + 2*Math.PI;
}
else if (orbitList.get(k).getRightAscensionOfAscendingNode() > 2*Math.PI) {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode() - 2*Math.PI;
}
else {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode();
}
ArgPerList.add(interArgPer);
//Print to File
System.out.println(orbitList.get(k).getA());
myWriter.write(String.valueOf(orbitList.get(k).getA()) + ";" + String.valueOf(orbitList.get(k).getE()) + ";" + String.valueOf(orbitList.get(k).getI()) + ";" + String.valueOf(interArgPer) + ";" + String.valueOf(orbitList.get(k).getRightAscensionOfAscendingNode()) + "\n");
}
myWriter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
BasicPlot plotter = new BasicPlot(); //creating plotter class
List<Double> AList = orbitList.stream().map(KeplerianOrbit::getA).collect(Collectors.toList()); //Semi-major Axis
// plotter.plot(AList, "Semi Major Axis" ,"DSSTA");
List<Double> EList = orbitList.stream().map(KeplerianOrbit::getE).collect(Collectors.toList()); //Eccentricity
// plotter.plot(EList, "Eccentricity" ,"DSSTE");
List<Double> IList = orbitList.stream().map(KeplerianOrbit::getI).collect(Collectors.toList()); //Inclination
// plotter.plot(IList, "Inclination" ,"DSSTI");
// plotter.plot(ArgPerList, "Argument of the Perigee" ,"DSSTAP"); //Argument of the Perigee
List<Double> RaanList = orbitList.stream().map(KeplerianOrbit::getRightAscensionOfAscendingNode).collect(Collectors.toList()); //Rigth Ascension of the Ascending Node
//plotter.plot(RaanList, "Right Ascension of Ascending Node" ,"DSSTRaan");
System.out.println("Successfully wrote to the file.");
}catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
}
}
}
| TOLOSAT/mission-analysis | orekit/src/main/java/quickTest/DSSTPropagation.java | 2,899 | // semi major axis in meters | line_comment | nl | package quickTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.hipparchus.ode.AbstractIntegrator;
import org.hipparchus.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.errors.OrekitException;
import org.orekit.forces.drag.DragSensitive;
import org.orekit.forces.drag.IsotropicDrag;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.IsotropicRadiationSingleCoefficient;
import org.orekit.forces.radiation.RadiationSensitive;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.models.earth.atmosphere.HarrisPriester;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.EphemerisGenerator;
import org.orekit.propagation.PropagationType;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTTesseral;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTZonal;
public class DSSTPropagation {
/** Private constructor for utility class. */
private DSSTPropagation() {
// empty
}
public static void main(final String[] args) {
try {
// configure Orekit
final File home = new File(System.getProperty("user.home"));
final File orekitData = new File(home, "orekit-data");
if (!orekitData.exists()) {
System.err.format(Locale.US, "Failed to find %s folder%n",
orekitData.getAbsolutePath());
System.err.format(Locale.US, "You need to download %s from %s, unzip it in %s and rename it 'orekit-data' for this tutorial to work%n",
"orekit-data-master.zip", "https://gitlab.orekit.org/orekit/orekit-data/-/archive/master/orekit-data-master.zip",
home.getAbsolutePath());
System.exit(1);
}
final DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();
manager.addProvider(new DirectoryCrawler(orekitData));
// gravitation coefficient
final double mu = 3.986004415e+14;
// inertial frame
final Frame inertialFrame = FramesFactory.getEME2000();
// Load Celestial bodies
// ---------------------
final CelestialBody sun = CelestialBodyFactory.getSun();
// Initial date
final AbsoluteDate initialDate = new AbsoluteDate(2024,07,02,12,0,0,TimeScalesFactory.getUTC());
// Initial orbit
final double RE = Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS;
final double a = 6878.e3; // semi major<SUF>
final double ecc = 2.e-2; // eccentricity
final double i = 97.4009688*Math.PI/180; // inclination
final double omega =Math.PI/2; // perigee argument
final double raan = 0; // right ascention of ascending node
final double lM = 0; // mean anomaly
final Orbit initialOrbit = new KeplerianOrbit(a, ecc, i, omega, raan, lM, PositionAngle.MEAN,
inertialFrame, initialDate, mu);
final double fixedStepSize = 2*Math.PI*Math.sqrt((a*a*a)/mu);
final int datastep = 100; // Interval between recorded data points on output file
final int duration = 500*86400;// in seconds
final double mass= 2.66;
final AbsoluteDate start = initialOrbit.getDate();
int output_step = 8600;
// All dates in UTC
final TimeScale utc = TimeScalesFactory.getUTC();
final double rotationRate = Constants.WGS84_EARTH_ANGULAR_VELOCITY;
// Defining the Propagator
final AbstractIntegrator integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
final PropagationType outputType = PropagationType.MEAN;
final DSSTPropagator propagator = new DSSTPropagator(integrator, outputType);
propagator.setInitialState(new SpacecraftState(initialOrbit, mass), PropagationType.MEAN);
//Models
final IERSConventions conventions = IERSConventions.IERS_2010;
final Frame earthFrame = FramesFactory.getITRF(conventions, false);
final OneAxisEllipsoid earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
Constants.WGS84_EARTH_FLATTENING,
earthFrame);
// Gravity Field Force Model
final int ZonalMaxDegree = 15;
final int ZonalMaxOrder = 15;
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(ZonalMaxDegree, ZonalMaxOrder);
propagator.addForceModel(new DSSTZonal(unnormalized));
propagator.addForceModel(new DSSTTesseral(earthFrame, rotationRate, unnormalized));
// Atmosphere
final HarrisPriester atmos = new HarrisPriester(sun,earth);
// Drag
double crossArea = 0.025;
double Cd = 2.2;
DragSensitive ssc = new IsotropicDrag(crossArea, Cd);
propagator.addForceModel(new DSSTAtmosphericDrag(atmos, ssc, mu));
// Solar Radiation Pressure
double cR = 1.8;
double srpArea = 0.025;
final RadiationSensitive ssrc = new IsotropicRadiationSingleCoefficient(srpArea, cR);
propagator.addForceModel(new DSSTSolarRadiationPressure(sun, RE, ssrc, mu));
//Propagation
final EphemerisGenerator dsstGenerator = propagator.getEphemerisGenerator();
final double dsstOn = System.currentTimeMillis();
propagator.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time (without large file write) : " + (dsstOff - dsstOn) / 1000.);
final BoundedPropagator ephemeris = dsstGenerator.getGeneratedEphemeris();
System.out.format("%nEphemeris defined from %s to %s%n", ephemeris.getMinDate(), ephemeris.getMaxDate());
//Initialization of list of orbit ephemeris
ArrayList<KeplerianOrbit> orbitList = new ArrayList<>();
double interArgPer = 0;
List<Double> ArgPerList = new ArrayList<>();
//Writing the results to a text file
try {
FileWriter myWriter = new FileWriter("output/DSSTPropagation.txt");
//Writing Header
myWriter.write(" Semi-Major Axis ; Eccentricity ; Inclination ; Argument of the perigee ; Right Ascension of the Ascending node\n");
//Get values from ephemeris
for (int k = 0; k < duration/output_step; k= k + 1) {
AbsoluteDate intermediateDate = initialDate.shiftedBy(output_step*i);
SpacecraftState intermediateState = ephemeris.propagate(intermediateDate);
orbitList.add(new KeplerianOrbit(intermediateState.getOrbit()));
//Normalize Argument of the Perigee
if (orbitList.get(k).getRightAscensionOfAscendingNode() < - 2*Math.PI) {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode() + 2*Math.PI;
}
else if (orbitList.get(k).getRightAscensionOfAscendingNode() > 2*Math.PI) {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode() - 2*Math.PI;
}
else {
interArgPer = orbitList.get(k).getRightAscensionOfAscendingNode();
}
ArgPerList.add(interArgPer);
//Print to File
System.out.println(orbitList.get(k).getA());
myWriter.write(String.valueOf(orbitList.get(k).getA()) + ";" + String.valueOf(orbitList.get(k).getE()) + ";" + String.valueOf(orbitList.get(k).getI()) + ";" + String.valueOf(interArgPer) + ";" + String.valueOf(orbitList.get(k).getRightAscensionOfAscendingNode()) + "\n");
}
myWriter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
BasicPlot plotter = new BasicPlot(); //creating plotter class
List<Double> AList = orbitList.stream().map(KeplerianOrbit::getA).collect(Collectors.toList()); //Semi-major Axis
// plotter.plot(AList, "Semi Major Axis" ,"DSSTA");
List<Double> EList = orbitList.stream().map(KeplerianOrbit::getE).collect(Collectors.toList()); //Eccentricity
// plotter.plot(EList, "Eccentricity" ,"DSSTE");
List<Double> IList = orbitList.stream().map(KeplerianOrbit::getI).collect(Collectors.toList()); //Inclination
// plotter.plot(IList, "Inclination" ,"DSSTI");
// plotter.plot(ArgPerList, "Argument of the Perigee" ,"DSSTAP"); //Argument of the Perigee
List<Double> RaanList = orbitList.stream().map(KeplerianOrbit::getRightAscensionOfAscendingNode).collect(Collectors.toList()); //Rigth Ascension of the Ascending Node
//plotter.plot(RaanList, "Right Ascension of Ascending Node" ,"DSSTRaan");
System.out.println("Successfully wrote to the file.");
}catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
}
}
}
|
209775_2 | package quickTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.hipparchus.ode.AbstractIntegrator;
import org.hipparchus.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.hipparchus.util.FastMath;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.errors.OrekitException;
import org.orekit.forces.drag.DragSensitive;
import org.orekit.forces.drag.IsotropicDrag;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.IsotropicRadiationSingleCoefficient;
import org.orekit.forces.radiation.RadiationSensitive;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.models.earth.atmosphere.HarrisPriester;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.PropagationType;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTTesseral;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTZonal;
import org.orekit.propagation.events.AltitudeDetector;
import org.orekit.models.earth.atmosphere.data.MarshallSolarActivityFutureEstimation;
import org.orekit.models.earth.atmosphere.NRLMSISE00;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.utils.PVCoordinates;
import quickTest.PathCreator.AppFrame;
import org.orekit.frames.Transform;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwindx.examples.ApplicationTemplate;
public class DSSTPropagationMux {
/** Private constructor for utility class. */
private DSSTPropagationMux() {
// empty
}
static ArrayList<KeplerianOrbit> orbitList = new ArrayList<>();
static ArrayList<GeodeticPoint> listOfStates = new ArrayList<GeodeticPoint>();
static OneAxisEllipsoid earth;
static AbsoluteDate initialDate = new AbsoluteDate();
public static void main(final String[] args) {
try {
// configure Orekit
final File home = new File(System.getProperty("user.home"));
final File orekitData = new File(home, "orekit-data");
if (!orekitData.exists()) {
System.err.format(Locale.US, "Failed to find %s folder%n",
orekitData.getAbsolutePath());
System.err.format(Locale.US, "You need to download %s from %s, unzip it in %s and rename it 'orekit-data' for this tutorial to work%n",
"orekit-data-master.zip", "https://gitlab.orekit.org/orekit/orekit-data/-/archive/master/orekit-data-master.zip",
home.getAbsolutePath());
System.exit(1);
}
final DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();
manager.addProvider(new DirectoryCrawler(orekitData));
// gravitation coefficient
final double mu = 3.986004415e+14;
// inertial frame
final Frame inertialFrame = FramesFactory.getEME2000();
// Load Celestial bodies
// ---------------------
final CelestialBody sun = CelestialBodyFactory.getSun();
// Initial date
initialDate = new AbsoluteDate(2024,07,02,12,0,0,TimeScalesFactory.getUTC());
// Initial orbit
final double RE = Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS;
final double a = 6878.e3; // semi major axis in meters
final double ecc = 2.e-2; // eccentricity
final double i = 97.4009688*Math.PI/180; // inclination
final double omega =Math.PI/2; // perigee argument
final double raan = 0; // right ascention of ascending node
final double lM = 0; // mean anomaly
final Orbit initialOrbit = new KeplerianOrbit(a, ecc, i, omega, raan, lM, PositionAngle.MEAN,
inertialFrame, initialDate, mu);
final double fixedStepSize = 2*Math.PI*Math.sqrt((a*a*a)/mu);
final int datastep = 1; // Interval between recorded data points on output file
final int duration = 160000*86400;// in seconds
final double mass= 2.66;
final AbsoluteDate start = initialOrbit.getDate();
final double rotationRate = Constants.WGS84_EARTH_ANGULAR_VELOCITY;
// Defining the Propagator
final AbstractIntegrator integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
final PropagationType outputType = PropagationType.MEAN;
final DSSTPropagator propagator = new DSSTPropagator(integrator, outputType);
propagator.setInitialState(new SpacecraftState(initialOrbit, mass), PropagationType.MEAN);
//Models
final IERSConventions conventions = IERSConventions.IERS_2010;
final Frame earthFrame = FramesFactory.getITRF(conventions, false);
earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
Constants.WGS84_EARTH_FLATTENING,
earthFrame);
// Gravity Field Force Model
final int ZonalMaxDegree = 15;
final int ZonalMaxOrder = 15;
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(ZonalMaxDegree, ZonalMaxOrder);
propagator.addForceModel(new DSSTZonal(unnormalized));
propagator.addForceModel(new DSSTTesseral(earthFrame, rotationRate, unnormalized));
// Atmosphere
//final HarrisPriester atmos = new HarrisPriester(sun,earth);
final MarshallSolarActivityFutureEstimation parameters = new MarshallSolarActivityFutureEstimation(MarshallSolarActivityFutureEstimation.DEFAULT_SUPPORTED_NAMES, MarshallSolarActivityFutureEstimation.StrengthLevel.AVERAGE);
final NRLMSISE00 atmos = new NRLMSISE00(parameters, sun, earth);
// Drag
double crossArea = 0.025;
double Cd = 2.2;
DragSensitive ssc = new IsotropicDrag(crossArea, Cd);
propagator.addForceModel(new DSSTAtmosphericDrag(atmos, ssc, mu));
// Solar Radiation Pressure
double cR = 1.8;
double srpArea = 0.025;
final RadiationSensitive ssrc = new IsotropicRadiationSingleCoefficient(srpArea, cR);
propagator.addForceModel(new DSSTSolarRadiationPressure(sun, RE, ssrc, mu));
// Stopping when altitude too low
final double MinAlt = 140000;
final EventDetector LowAlt = new AltitudeDetector(MinAlt, earth);
propagator.addEventDetector(LowAlt);
//Propagation
propagator.getMultiplexer().add(8600, new TestStepHandler());
final double dsstOn = System.currentTimeMillis();
propagator.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time (without large file write) : " + (dsstOff - dsstOn) / 1000.);
//Writing the results to a text file
new WriteToFile("output/DSSTPropagation.txt",datastep);
BasicPlot plotter = new BasicPlot(); //creating plotter class
List<AbsoluteDate> DateList = orbitList.stream().map(KeplerianOrbit::getDate).collect(Collectors.toList());
List<Double> TimeList = new ArrayList<>();
for (AbsoluteDate D : DateList) {
TimeList.add(D.durationFrom(initialDate)/(24*3600));
}
List<Double> AList = orbitList.stream().map(KeplerianOrbit::getA).collect(Collectors.toList());
plotter.plot(TimeList, AList, "Semi Major Axis" ,"DSSTA", "Semi-Analytical");
ArrayList<Double> AltList = new ArrayList<>();
for (double r : AList) {
AltList.add(r-RE);
}
plotter.plot(TimeList, AltList, "Altitude" ,"DSSTAlt", "Semi-Analytical");
List<Double> EList = orbitList.stream().map(KeplerianOrbit::getE).collect(Collectors.toList()); //Eccentricity
plotter.plot(TimeList, EList, "Eccentricity" ,"DSSTE", "Semi-Analytical");
List<Double> IList = orbitList.stream().map(KeplerianOrbit::getI).collect(Collectors.toList()); //Inclination
plotter.plot(TimeList, IList, "Inclination" ,"DSSTI", "Semi-Analytical");
List<Double> APList = orbitList.stream().map(KeplerianOrbit::getPerigeeArgument).collect(Collectors.toList());
plotter.plot(TimeList, APList, "Argument of the Perigee" ,"DSSTAP", "Semi-Analytical");
List<Double> RaanList = orbitList.stream().map(KeplerianOrbit::getRightAscensionOfAscendingNode).collect(Collectors.toList());
plotter.plot(TimeList, RaanList, "Right Ascension of Ascending Node" ,"DSSTRaan", "Semi-Analytical");
System.out.println("Successfully wrote to the file.");
//new PathCreator(listOfStates);
//System.setProperty("http.proxyHost", "proxy.isae.fr");
//System.setProperty("http.proxyPort", "3128");
//WorldWind.setOfflineMode(true);
//ApplicationTemplate.start("WorldWind Paths", AppFrame.class);
}catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
}
}
private static class TestStepHandler implements OrekitFixedStepHandler {
/** Simple constructor.
*/
TestStepHandler() {
//private constructor
}
/** {@inheritDoc} */
@Override
public void init(final SpacecraftState s0, final AbsoluteDate t, final double step) {
}
/** {@inheritDoc} */
@Override
public void handleStep(final SpacecraftState currentState) {
final KeplerianOrbit o = (KeplerianOrbit) OrbitType.KEPLERIAN.convertType(currentState.getOrbit());
orbitList.add(o);
/* // compute sub-satellite track
AbsoluteDate date = currentState.getDate();
PVCoordinates pvInert = currentState.getPVCoordinates();
Transform t;
t = currentState.getFrame().getTransformTo(earth.getBodyFrame(), date);
Vector3D p = t.transformPosition(pvInert.getPosition());
GeodeticPoint center = earth.transform(p, earth.getBodyFrame(), date);
listOfStates.add(center); */
}
/** {@inheritDoc} */
@Override
public void finish(final SpacecraftState finalState) {
System.out.println("this was the last step ");
System.out.println();
}
}
private static class WriteToFile{
WriteToFile(String filename, int dataStep) {
try {
FileWriter myWriter = new FileWriter(filename);
myWriter.write("Time ; Semi-Major Axis ; Eccentricity ; Inclination ; Argument of the perigee ; Right Ascension of the Ascending node\n");
int i = -1;
int previ = 0;
for(KeplerianOrbit o : orbitList) {
i += 1;
if( i-previ == 0 || i-previ == dataStep) {
myWriter.write( String.valueOf(o.getDate().durationFrom(initialDate)) + ";"
+ String.valueOf(o.getA()) + ";"
+ String.valueOf(o.getE()) + ";"
+ String.valueOf(FastMath.toDegrees(o.getI())) + ";"
+ String.valueOf(FastMath.toDegrees(o.getPerigeeArgument())) + ";"
+ String.valueOf(FastMath.toDegrees(o.getTrueAnomaly())) + "\n");
previ = i;
}
}
myWriter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
}
| TOLOSAT/mission-analysis | orekit/src/main/java/quickTest/DSSTPropagationMux.java | 3,538 | // semi major axis in meters | line_comment | nl | package quickTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.hipparchus.ode.AbstractIntegrator;
import org.hipparchus.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.hipparchus.util.FastMath;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.errors.OrekitException;
import org.orekit.forces.drag.DragSensitive;
import org.orekit.forces.drag.IsotropicDrag;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.radiation.IsotropicRadiationSingleCoefficient;
import org.orekit.forces.radiation.RadiationSensitive;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.models.earth.atmosphere.HarrisPriester;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.PropagationType;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTTesseral;
import org.orekit.propagation.semianalytical.dsst.forces.DSSTZonal;
import org.orekit.propagation.events.AltitudeDetector;
import org.orekit.models.earth.atmosphere.data.MarshallSolarActivityFutureEstimation;
import org.orekit.models.earth.atmosphere.NRLMSISE00;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.utils.PVCoordinates;
import quickTest.PathCreator.AppFrame;
import org.orekit.frames.Transform;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwindx.examples.ApplicationTemplate;
public class DSSTPropagationMux {
/** Private constructor for utility class. */
private DSSTPropagationMux() {
// empty
}
static ArrayList<KeplerianOrbit> orbitList = new ArrayList<>();
static ArrayList<GeodeticPoint> listOfStates = new ArrayList<GeodeticPoint>();
static OneAxisEllipsoid earth;
static AbsoluteDate initialDate = new AbsoluteDate();
public static void main(final String[] args) {
try {
// configure Orekit
final File home = new File(System.getProperty("user.home"));
final File orekitData = new File(home, "orekit-data");
if (!orekitData.exists()) {
System.err.format(Locale.US, "Failed to find %s folder%n",
orekitData.getAbsolutePath());
System.err.format(Locale.US, "You need to download %s from %s, unzip it in %s and rename it 'orekit-data' for this tutorial to work%n",
"orekit-data-master.zip", "https://gitlab.orekit.org/orekit/orekit-data/-/archive/master/orekit-data-master.zip",
home.getAbsolutePath());
System.exit(1);
}
final DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();
manager.addProvider(new DirectoryCrawler(orekitData));
// gravitation coefficient
final double mu = 3.986004415e+14;
// inertial frame
final Frame inertialFrame = FramesFactory.getEME2000();
// Load Celestial bodies
// ---------------------
final CelestialBody sun = CelestialBodyFactory.getSun();
// Initial date
initialDate = new AbsoluteDate(2024,07,02,12,0,0,TimeScalesFactory.getUTC());
// Initial orbit
final double RE = Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS;
final double a = 6878.e3; // semi major<SUF>
final double ecc = 2.e-2; // eccentricity
final double i = 97.4009688*Math.PI/180; // inclination
final double omega =Math.PI/2; // perigee argument
final double raan = 0; // right ascention of ascending node
final double lM = 0; // mean anomaly
final Orbit initialOrbit = new KeplerianOrbit(a, ecc, i, omega, raan, lM, PositionAngle.MEAN,
inertialFrame, initialDate, mu);
final double fixedStepSize = 2*Math.PI*Math.sqrt((a*a*a)/mu);
final int datastep = 1; // Interval between recorded data points on output file
final int duration = 160000*86400;// in seconds
final double mass= 2.66;
final AbsoluteDate start = initialOrbit.getDate();
final double rotationRate = Constants.WGS84_EARTH_ANGULAR_VELOCITY;
// Defining the Propagator
final AbstractIntegrator integrator = new ClassicalRungeKuttaIntegrator(fixedStepSize);
final PropagationType outputType = PropagationType.MEAN;
final DSSTPropagator propagator = new DSSTPropagator(integrator, outputType);
propagator.setInitialState(new SpacecraftState(initialOrbit, mass), PropagationType.MEAN);
//Models
final IERSConventions conventions = IERSConventions.IERS_2010;
final Frame earthFrame = FramesFactory.getITRF(conventions, false);
earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
Constants.WGS84_EARTH_FLATTENING,
earthFrame);
// Gravity Field Force Model
final int ZonalMaxDegree = 15;
final int ZonalMaxOrder = 15;
final UnnormalizedSphericalHarmonicsProvider unnormalized =
GravityFieldFactory.getConstantUnnormalizedProvider(ZonalMaxDegree, ZonalMaxOrder);
propagator.addForceModel(new DSSTZonal(unnormalized));
propagator.addForceModel(new DSSTTesseral(earthFrame, rotationRate, unnormalized));
// Atmosphere
//final HarrisPriester atmos = new HarrisPriester(sun,earth);
final MarshallSolarActivityFutureEstimation parameters = new MarshallSolarActivityFutureEstimation(MarshallSolarActivityFutureEstimation.DEFAULT_SUPPORTED_NAMES, MarshallSolarActivityFutureEstimation.StrengthLevel.AVERAGE);
final NRLMSISE00 atmos = new NRLMSISE00(parameters, sun, earth);
// Drag
double crossArea = 0.025;
double Cd = 2.2;
DragSensitive ssc = new IsotropicDrag(crossArea, Cd);
propagator.addForceModel(new DSSTAtmosphericDrag(atmos, ssc, mu));
// Solar Radiation Pressure
double cR = 1.8;
double srpArea = 0.025;
final RadiationSensitive ssrc = new IsotropicRadiationSingleCoefficient(srpArea, cR);
propagator.addForceModel(new DSSTSolarRadiationPressure(sun, RE, ssrc, mu));
// Stopping when altitude too low
final double MinAlt = 140000;
final EventDetector LowAlt = new AltitudeDetector(MinAlt, earth);
propagator.addEventDetector(LowAlt);
//Propagation
propagator.getMultiplexer().add(8600, new TestStepHandler());
final double dsstOn = System.currentTimeMillis();
propagator.propagate(start, start.shiftedBy(duration));
final double dsstOff = System.currentTimeMillis();
System.out.println("DSST execution time (without large file write) : " + (dsstOff - dsstOn) / 1000.);
//Writing the results to a text file
new WriteToFile("output/DSSTPropagation.txt",datastep);
BasicPlot plotter = new BasicPlot(); //creating plotter class
List<AbsoluteDate> DateList = orbitList.stream().map(KeplerianOrbit::getDate).collect(Collectors.toList());
List<Double> TimeList = new ArrayList<>();
for (AbsoluteDate D : DateList) {
TimeList.add(D.durationFrom(initialDate)/(24*3600));
}
List<Double> AList = orbitList.stream().map(KeplerianOrbit::getA).collect(Collectors.toList());
plotter.plot(TimeList, AList, "Semi Major Axis" ,"DSSTA", "Semi-Analytical");
ArrayList<Double> AltList = new ArrayList<>();
for (double r : AList) {
AltList.add(r-RE);
}
plotter.plot(TimeList, AltList, "Altitude" ,"DSSTAlt", "Semi-Analytical");
List<Double> EList = orbitList.stream().map(KeplerianOrbit::getE).collect(Collectors.toList()); //Eccentricity
plotter.plot(TimeList, EList, "Eccentricity" ,"DSSTE", "Semi-Analytical");
List<Double> IList = orbitList.stream().map(KeplerianOrbit::getI).collect(Collectors.toList()); //Inclination
plotter.plot(TimeList, IList, "Inclination" ,"DSSTI", "Semi-Analytical");
List<Double> APList = orbitList.stream().map(KeplerianOrbit::getPerigeeArgument).collect(Collectors.toList());
plotter.plot(TimeList, APList, "Argument of the Perigee" ,"DSSTAP", "Semi-Analytical");
List<Double> RaanList = orbitList.stream().map(KeplerianOrbit::getRightAscensionOfAscendingNode).collect(Collectors.toList());
plotter.plot(TimeList, RaanList, "Right Ascension of Ascending Node" ,"DSSTRaan", "Semi-Analytical");
System.out.println("Successfully wrote to the file.");
//new PathCreator(listOfStates);
//System.setProperty("http.proxyHost", "proxy.isae.fr");
//System.setProperty("http.proxyPort", "3128");
//WorldWind.setOfflineMode(true);
//ApplicationTemplate.start("WorldWind Paths", AppFrame.class);
}catch (OrekitException oe) {
System.err.println(oe.getLocalizedMessage());
}
}
private static class TestStepHandler implements OrekitFixedStepHandler {
/** Simple constructor.
*/
TestStepHandler() {
//private constructor
}
/** {@inheritDoc} */
@Override
public void init(final SpacecraftState s0, final AbsoluteDate t, final double step) {
}
/** {@inheritDoc} */
@Override
public void handleStep(final SpacecraftState currentState) {
final KeplerianOrbit o = (KeplerianOrbit) OrbitType.KEPLERIAN.convertType(currentState.getOrbit());
orbitList.add(o);
/* // compute sub-satellite track
AbsoluteDate date = currentState.getDate();
PVCoordinates pvInert = currentState.getPVCoordinates();
Transform t;
t = currentState.getFrame().getTransformTo(earth.getBodyFrame(), date);
Vector3D p = t.transformPosition(pvInert.getPosition());
GeodeticPoint center = earth.transform(p, earth.getBodyFrame(), date);
listOfStates.add(center); */
}
/** {@inheritDoc} */
@Override
public void finish(final SpacecraftState finalState) {
System.out.println("this was the last step ");
System.out.println();
}
}
private static class WriteToFile{
WriteToFile(String filename, int dataStep) {
try {
FileWriter myWriter = new FileWriter(filename);
myWriter.write("Time ; Semi-Major Axis ; Eccentricity ; Inclination ; Argument of the perigee ; Right Ascension of the Ascending node\n");
int i = -1;
int previ = 0;
for(KeplerianOrbit o : orbitList) {
i += 1;
if( i-previ == 0 || i-previ == dataStep) {
myWriter.write( String.valueOf(o.getDate().durationFrom(initialDate)) + ";"
+ String.valueOf(o.getA()) + ";"
+ String.valueOf(o.getE()) + ";"
+ String.valueOf(FastMath.toDegrees(o.getI())) + ";"
+ String.valueOf(FastMath.toDegrees(o.getPerigeeArgument())) + ";"
+ String.valueOf(FastMath.toDegrees(o.getTrueAnomaly())) + "\n");
previ = i;
}
}
myWriter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
}
|
209802_7 | /*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package jdk.internal.org.objectweb.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| openjdk/jdk | src/java.base/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/SmallSet.java | 2,063 | /**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/ | block_comment | nl | /*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package jdk.internal.org.objectweb.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new<SUF>*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
209835_29 | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package nginx.clojure.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| nginx-clojure/nginx-clojure | src/java/nginx/clojure/asm/tree/analysis/SmallSet.java | 1,726 | /**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/ | block_comment | nl | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package nginx.clojure.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new<SUF>*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
210000_2 |
import java.awt.Color;
import java.awt.Graphics;
import java.util.EnumMap;
import java.util.Map;
import javax.sound.sampled.Line;
/*
* 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.
*/
/**
*
* @author My sony
*/
public class Cell {
private int x;
private int y;
private int height;
private int width;
private EnumMap<Direction, Cell> neighbours = new EnumMap<>(Direction.class);
private EnumMap<Direction, Wall> muren = new EnumMap<>(Direction.class);
private Ghost ghost;
private Pacman pacman;
private boolean visited = false;
public Cell(int xpos, int ypos , int height, int width ){
this.x = xpos;
this.y = ypos;
this.height = height;
this.width = width;
init();
}
public void draw(Graphics g){
for(Wall wall: muren.values()){
wall.draw(g);
}
}
private void init() {
Wall NORTH = new Wall(x, y, x + width, y);
Wall WEST = new Wall(x, y, x, y + height);
Wall EAST = new Wall(x + width, y, x + width, y + height);
Wall SOUTH = new Wall(x, y + height, x + width, y + height);
muren.put(Direction.WEST, WEST);
muren.put(Direction.EAST, EAST);
muren.put(Direction.SOUTH, SOUTH);
muren.put(Direction.NORTH, NORTH);
}
public void setNeighbours(EnumMap<Direction, Cell> neighnours) {
neighbours.putAll(neighnours);
}
Map<Direction, Cell> getUnvisitedNeighbours() {
EnumMap<Direction, Cell> uCell = new EnumMap<>(Direction.class);
Object uCellList[] = neighbours.values().toArray();
for(int i =0; i< uCellList.length; i++){
Cell neighbourCell = (Cell)uCellList[1];
if(!neighbourCell.isVisited()){
uCell.put(getKeyByValue(neighbours,neighbourCell), neighbourCell);
}
}
return uCell;
}
//return de key van een map
private static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
public boolean isVisited() {
return visited;
}
}
| shawoozy/pacman | src/Cell.java | 726 | //return de key van een map
| line_comment | nl |
import java.awt.Color;
import java.awt.Graphics;
import java.util.EnumMap;
import java.util.Map;
import javax.sound.sampled.Line;
/*
* 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.
*/
/**
*
* @author My sony
*/
public class Cell {
private int x;
private int y;
private int height;
private int width;
private EnumMap<Direction, Cell> neighbours = new EnumMap<>(Direction.class);
private EnumMap<Direction, Wall> muren = new EnumMap<>(Direction.class);
private Ghost ghost;
private Pacman pacman;
private boolean visited = false;
public Cell(int xpos, int ypos , int height, int width ){
this.x = xpos;
this.y = ypos;
this.height = height;
this.width = width;
init();
}
public void draw(Graphics g){
for(Wall wall: muren.values()){
wall.draw(g);
}
}
private void init() {
Wall NORTH = new Wall(x, y, x + width, y);
Wall WEST = new Wall(x, y, x, y + height);
Wall EAST = new Wall(x + width, y, x + width, y + height);
Wall SOUTH = new Wall(x, y + height, x + width, y + height);
muren.put(Direction.WEST, WEST);
muren.put(Direction.EAST, EAST);
muren.put(Direction.SOUTH, SOUTH);
muren.put(Direction.NORTH, NORTH);
}
public void setNeighbours(EnumMap<Direction, Cell> neighnours) {
neighbours.putAll(neighnours);
}
Map<Direction, Cell> getUnvisitedNeighbours() {
EnumMap<Direction, Cell> uCell = new EnumMap<>(Direction.class);
Object uCellList[] = neighbours.values().toArray();
for(int i =0; i< uCellList.length; i++){
Cell neighbourCell = (Cell)uCellList[1];
if(!neighbourCell.isVisited()){
uCell.put(getKeyByValue(neighbours,neighbourCell), neighbourCell);
}
}
return uCell;
}
//return de<SUF>
private static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
public boolean isVisited() {
return visited;
}
}
|
210002_5 | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated using string template dis7javalicense.txt
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.fra.munition.antisubmarine;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>Murenetorpedo</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>Murenetorpedo.createInstance()</code> or <code>new Murenetorpedo()</code>. </p>
* <ul>
* <li> Country: France (FRA) = <code>71</code>; </li>
* <li> Entity kind: MunitionDomain = <code>ANTI_SUBMARINE</code>; </li>
* <li> Domain: Munition = <code>2</code>; </li>
* <li> Category: Guided = <code>1</code>; </li>
* <li> SubCategory: Murenetorpedo = <code>8</code>; </li>
* <li> Specific: null <code>(none)</code>; </li>
* <li> Entity type uid: 21126; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SubCategoryElem@39851c5. </p>
* @see Country#FRANCE_FRA
* @see EntityKind#MUNITION
* @see Domain
* @see MunitionDomain
* @see Category
* @see Guided
* @see SubCategory
*/
public final class Murenetorpedo extends EntityType
{
/** Default constructor */
public Murenetorpedo()
{
setCountry(Country.FRANCE_FRA);
setEntityKind(EntityKind.MUNITION);
setDomain(Domain.inst(MunitionDomain.ANTI_SUBMARINE));
setCategory((byte)1); // uid 21118, Guided
setSubCategory((byte)8); // uid 21126, Murene torpedo
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static Murenetorpedo createInstance()
{
return new Murenetorpedo();
}
}
| open-dis/opendis7-java | src-generated/edu/nps/moves/dis7/entities/fra/munition/antisubmarine/Murenetorpedo.java | 781 | // uid 21126, Murene torpedo | line_comment | nl | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated using string template dis7javalicense.txt
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.fra.munition.antisubmarine;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>Murenetorpedo</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>Murenetorpedo.createInstance()</code> or <code>new Murenetorpedo()</code>. </p>
* <ul>
* <li> Country: France (FRA) = <code>71</code>; </li>
* <li> Entity kind: MunitionDomain = <code>ANTI_SUBMARINE</code>; </li>
* <li> Domain: Munition = <code>2</code>; </li>
* <li> Category: Guided = <code>1</code>; </li>
* <li> SubCategory: Murenetorpedo = <code>8</code>; </li>
* <li> Specific: null <code>(none)</code>; </li>
* <li> Entity type uid: 21126; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SubCategoryElem@39851c5. </p>
* @see Country#FRANCE_FRA
* @see EntityKind#MUNITION
* @see Domain
* @see MunitionDomain
* @see Category
* @see Guided
* @see SubCategory
*/
public final class Murenetorpedo extends EntityType
{
/** Default constructor */
public Murenetorpedo()
{
setCountry(Country.FRANCE_FRA);
setEntityKind(EntityKind.MUNITION);
setDomain(Domain.inst(MunitionDomain.ANTI_SUBMARINE));
setCategory((byte)1); // uid 21118, Guided
setSubCategory((byte)8); // uid 21126,<SUF>
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static Murenetorpedo createInstance()
{
return new Murenetorpedo();
}
}
|
210037_4 | package Forms;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class adminnform implements ActionListener {
JFrame frame;
JLabel id_lb = new JLabel("ID");
JLabel fname_lb = new JLabel("First name");
JLabel lname_lb = new JLabel("Last Name");
JLabel email_lb = new JLabel("Email");
JLabel telephone_lb = new JLabel("Telephone");
// JLabel gender_lb = new JLabel("Gender");
JTextField id_txf = new JTextField();
JTextField first_name_txf = new JTextField();
JTextField last_name_txf = new JTextField();
JTextField email_txf = new JTextField();
JTextField telephone_txf = new JTextField();
// String[] gender = {"Male", "Female"};
// JComboBox<String> genderBox = new JComboBox<>(gender);
JButton insert_btn = new JButton("Insert");
JButton read_btn = new JButton("Read");
JButton update_btn = new JButton("Update");
JButton delete_btn = new JButton("Delete");
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
public adminnform() {
createForm();
}
private void createForm() {
frame = new JFrame();
frame.setTitle("ADMIN FORM");
frame.setBounds(350, 100, 400, 350);
frame.getContentPane().setLayout(null);
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
setLocationAndSize();
}
private void setLocationAndSize() {
id_lb.setBounds(10, 10, 100, 30);
fname_lb.setBounds(10, 50, 100, 30);
lname_lb.setBounds(10, 90, 100, 30);
email_lb.setBounds(10, 130, 100, 30);
telephone_lb.setBounds(10, 170, 100, 30);
// gender_lb.setBounds(10, 210, 100, 30);
id_txf.setBounds(160, 10, 130, 30);
first_name_txf.setBounds(160, 50, 130, 30);
last_name_txf.setBounds(160, 90, 130, 30);
email_txf.setBounds(160, 130, 130, 30);
telephone_txf.setBounds(160, 170, 130, 30);
// genderBox.setBounds(160, 210, 130, 30);
insert_btn.setBounds(10, 250, 85, 30);
read_btn.setBounds(100, 250, 85, 30);
update_btn.setBounds(190, 250, 85, 30);
delete_btn.setBounds(280, 250, 85, 30);
setFontForAll();
addComponentsForFrame();
}
private void setFontForAll() {
Font font = new Font("Georgia", Font.BOLD, 18);
id_lb.setFont(font);
fname_lb.setFont(font);
lname_lb.setFont(font);
email_lb.setFont(font);
telephone_lb.setFont(font);
// gender_lb.setFont(font);
id_txf.setFont(font);
first_name_txf.setFont(font);
last_name_txf.setFont(font);
email_txf.setFont(font);
telephone_txf.setFont(font);
// genderBox.setFont(font);
Font fonti = new Font("Georgia", Font.ITALIC, 12);
insert_btn.setFont(fonti);
read_btn.setFont(fonti);
update_btn.setFont(fonti);
delete_btn.setFont(fonti);
}
private void addComponentsForFrame() {
frame.add(id_lb);
frame.add(fname_lb);
frame.add(lname_lb);
frame.add(email_lb);
frame.add(telephone_lb);
// frame.add(gender_lb);
frame.add(id_txf);
frame.add(first_name_txf);
frame.add(last_name_txf);
frame.add(email_txf);
frame.add(telephone_txf);
// frame.add(genderBox);
frame.add(insert_btn);
frame.add(read_btn);
frame.add(update_btn);
frame.add(delete_btn);
insert_btn.addActionListener(this);
insert_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager
.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String query="INSERT INTO adminn VALUES(?,?,?,?,?)";
PreparedStatement pStatement=connection.prepareStatement(query);
pStatement.setInt(1,Integer.parseInt(id_txf.getText()));
pStatement.setString(2, first_name_txf.getText());
pStatement.setString(3, last_name_txf.getText());
pStatement.setString(4, email_txf.getText());
pStatement.setString(5, telephone_txf.getText());
// pStatement.setString(6, genderBox.getToolkit());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(insert_btn, "data inserted well");
pStatement.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
read_btn.addActionListener(this);
update_btn.addActionListener(this);
update_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="UPDATE adminn SET first_name=?,last_name=?,email=?, telephone=? WHERE id=?";
PreparedStatement stm=connection.prepareStatement(sql);
stm.setString(1, first_name_txf.getText());
stm.setString(2, last_name_txf.getText());
stm.setString(3, email_txf.getText());
stm.setString(4, telephone_txf.getText());
stm.setInt(5,Integer.parseInt(id_txf.getText()));
stm.executeUpdate();
JOptionPane.showMessageDialog(update_btn, "update data!");
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
delete_btn.addActionListener(this);
delete_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="DELETE FROM adminn WHERE id=?";
int brtxf=Integer.parseInt(JOptionPane.showInputDialog("Enter id to delete:"));
PreparedStatement stm=connection.prepareStatement(sql);
stm.setInt(1,brtxf);
JOptionPane.showMessageDialog(delete_btn, "recorded out!!!!!!!!!");
//Component delete;
stm.executeUpdate();
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
new adminnform();
}
}
| SamuelNiyo/SamuelNiyo | niyomurengezi_samuel_222008677/src/Forms/adminnform.java | 2,356 | // genderBox.setBounds(160, 210, 130, 30);
| line_comment | nl | package Forms;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class adminnform implements ActionListener {
JFrame frame;
JLabel id_lb = new JLabel("ID");
JLabel fname_lb = new JLabel("First name");
JLabel lname_lb = new JLabel("Last Name");
JLabel email_lb = new JLabel("Email");
JLabel telephone_lb = new JLabel("Telephone");
// JLabel gender_lb = new JLabel("Gender");
JTextField id_txf = new JTextField();
JTextField first_name_txf = new JTextField();
JTextField last_name_txf = new JTextField();
JTextField email_txf = new JTextField();
JTextField telephone_txf = new JTextField();
// String[] gender = {"Male", "Female"};
// JComboBox<String> genderBox = new JComboBox<>(gender);
JButton insert_btn = new JButton("Insert");
JButton read_btn = new JButton("Read");
JButton update_btn = new JButton("Update");
JButton delete_btn = new JButton("Delete");
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
public adminnform() {
createForm();
}
private void createForm() {
frame = new JFrame();
frame.setTitle("ADMIN FORM");
frame.setBounds(350, 100, 400, 350);
frame.getContentPane().setLayout(null);
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
setLocationAndSize();
}
private void setLocationAndSize() {
id_lb.setBounds(10, 10, 100, 30);
fname_lb.setBounds(10, 50, 100, 30);
lname_lb.setBounds(10, 90, 100, 30);
email_lb.setBounds(10, 130, 100, 30);
telephone_lb.setBounds(10, 170, 100, 30);
// gender_lb.setBounds(10, 210, 100, 30);
id_txf.setBounds(160, 10, 130, 30);
first_name_txf.setBounds(160, 50, 130, 30);
last_name_txf.setBounds(160, 90, 130, 30);
email_txf.setBounds(160, 130, 130, 30);
telephone_txf.setBounds(160, 170, 130, 30);
// genderBox.setBounds(160, 210,<SUF>
insert_btn.setBounds(10, 250, 85, 30);
read_btn.setBounds(100, 250, 85, 30);
update_btn.setBounds(190, 250, 85, 30);
delete_btn.setBounds(280, 250, 85, 30);
setFontForAll();
addComponentsForFrame();
}
private void setFontForAll() {
Font font = new Font("Georgia", Font.BOLD, 18);
id_lb.setFont(font);
fname_lb.setFont(font);
lname_lb.setFont(font);
email_lb.setFont(font);
telephone_lb.setFont(font);
// gender_lb.setFont(font);
id_txf.setFont(font);
first_name_txf.setFont(font);
last_name_txf.setFont(font);
email_txf.setFont(font);
telephone_txf.setFont(font);
// genderBox.setFont(font);
Font fonti = new Font("Georgia", Font.ITALIC, 12);
insert_btn.setFont(fonti);
read_btn.setFont(fonti);
update_btn.setFont(fonti);
delete_btn.setFont(fonti);
}
private void addComponentsForFrame() {
frame.add(id_lb);
frame.add(fname_lb);
frame.add(lname_lb);
frame.add(email_lb);
frame.add(telephone_lb);
// frame.add(gender_lb);
frame.add(id_txf);
frame.add(first_name_txf);
frame.add(last_name_txf);
frame.add(email_txf);
frame.add(telephone_txf);
// frame.add(genderBox);
frame.add(insert_btn);
frame.add(read_btn);
frame.add(update_btn);
frame.add(delete_btn);
insert_btn.addActionListener(this);
insert_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager
.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String query="INSERT INTO adminn VALUES(?,?,?,?,?)";
PreparedStatement pStatement=connection.prepareStatement(query);
pStatement.setInt(1,Integer.parseInt(id_txf.getText()));
pStatement.setString(2, first_name_txf.getText());
pStatement.setString(3, last_name_txf.getText());
pStatement.setString(4, email_txf.getText());
pStatement.setString(5, telephone_txf.getText());
// pStatement.setString(6, genderBox.getToolkit());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(insert_btn, "data inserted well");
pStatement.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
read_btn.addActionListener(this);
update_btn.addActionListener(this);
update_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="UPDATE adminn SET first_name=?,last_name=?,email=?, telephone=? WHERE id=?";
PreparedStatement stm=connection.prepareStatement(sql);
stm.setString(1, first_name_txf.getText());
stm.setString(2, last_name_txf.getText());
stm.setString(3, email_txf.getText());
stm.setString(4, telephone_txf.getText());
stm.setInt(5,Integer.parseInt(id_txf.getText()));
stm.executeUpdate();
JOptionPane.showMessageDialog(update_btn, "update data!");
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
delete_btn.addActionListener(this);
delete_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="DELETE FROM adminn WHERE id=?";
int brtxf=Integer.parseInt(JOptionPane.showInputDialog("Enter id to delete:"));
PreparedStatement stm=connection.prepareStatement(sql);
stm.setInt(1,brtxf);
JOptionPane.showMessageDialog(delete_btn, "recorded out!!!!!!!!!");
//Component delete;
stm.executeUpdate();
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
new adminnform();
}
}
|
210047_4 | package adminlogin;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
//import menu.Menu;
import menu.menu;
import signupsetters.signup;
public class admin_login extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField emailTextField;
private JPasswordField passwordField;
public static void main(String[] args) {
// Launch the application
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
admin_login frame = new admin_login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public admin_login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 406, 329);
setTitle("Admin Login"); // Set frame title
contentPane = new JPanel();
contentPane.setBackground(Color.GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel emailLabel = new JLabel("Email:");
emailLabel.setFont(new Font("Times New Roman", Font.BOLD, 16));
emailLabel.setBounds(86, 69, 46, 14);
contentPane.add(emailLabel);
emailTextField = new JTextField();
emailTextField.setBackground(new Color(245, 245, 245));
emailTextField.setBounds(86, 94, 214, 34);
contentPane.add(emailTextField);
emailTextField.setColumns(10);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setFont(new Font("Times New Roman", Font.BOLD, 16));
passwordLabel.setBounds(86, 135, 91, 14);
contentPane.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBackground(new Color(245, 245, 245));
passwordField.setBounds(86, 160, 214, 34);
contentPane.add(passwordField);
JButton loginButton = new JButton("LOGIN");
loginButton.setBackground(new Color(25, 25, 112));
loginButton.setForeground(new Color(255, 255, 255));
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = emailTextField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);
// Simulating login process
// Replace this with actual login logic
if (username.equals("12345") && password.equals("12345")) {
// Login successful
JOptionPane.showMessageDialog(contentPane, "Login successful");
// Open user menu window
SwingUtilities.invokeLater(() -> new menu(username));
} else {
// Login failed
JOptionPane.showMessageDialog(contentPane, "Invalid username or password");
}
}
});
loginButton.setBounds(88, 225, 212, 39);
contentPane.add(loginButton);
JButton forgotPasswordButton = new JButton("Forgot Password?");
forgotPasswordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Logic for handling forgot password
// For demonstration purposes, just showing a message dialog
JOptionPane.showMessageDialog(contentPane, "Please contact administrator for password reset.");
}
});
forgotPasswordButton.setBounds(115, 275, 150, 30);
contentPane.add(forgotPasswordButton);
JButton createAccountButton = new JButton("Create New Account");
createAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Open registration form
signup registrationForm = new signup();
registrationForm.setVisible(true);
// Hide the current login frame
setVisible(false);
}
});
createAccountButton.setBounds(88, 320, 212, 39);
contentPane.add(createAccountButton);
}
}
| SamuelNiyo/SamuelNiyo | niyomurengezi_samuel_222008677/src/adminlogin/admin_login.java | 1,187 | // Open user menu window
| line_comment | nl | package adminlogin;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
//import menu.Menu;
import menu.menu;
import signupsetters.signup;
public class admin_login extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField emailTextField;
private JPasswordField passwordField;
public static void main(String[] args) {
// Launch the application
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
admin_login frame = new admin_login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public admin_login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 406, 329);
setTitle("Admin Login"); // Set frame title
contentPane = new JPanel();
contentPane.setBackground(Color.GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel emailLabel = new JLabel("Email:");
emailLabel.setFont(new Font("Times New Roman", Font.BOLD, 16));
emailLabel.setBounds(86, 69, 46, 14);
contentPane.add(emailLabel);
emailTextField = new JTextField();
emailTextField.setBackground(new Color(245, 245, 245));
emailTextField.setBounds(86, 94, 214, 34);
contentPane.add(emailTextField);
emailTextField.setColumns(10);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setFont(new Font("Times New Roman", Font.BOLD, 16));
passwordLabel.setBounds(86, 135, 91, 14);
contentPane.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBackground(new Color(245, 245, 245));
passwordField.setBounds(86, 160, 214, 34);
contentPane.add(passwordField);
JButton loginButton = new JButton("LOGIN");
loginButton.setBackground(new Color(25, 25, 112));
loginButton.setForeground(new Color(255, 255, 255));
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = emailTextField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);
// Simulating login process
// Replace this with actual login logic
if (username.equals("12345") && password.equals("12345")) {
// Login successful
JOptionPane.showMessageDialog(contentPane, "Login successful");
// Open user<SUF>
SwingUtilities.invokeLater(() -> new menu(username));
} else {
// Login failed
JOptionPane.showMessageDialog(contentPane, "Invalid username or password");
}
}
});
loginButton.setBounds(88, 225, 212, 39);
contentPane.add(loginButton);
JButton forgotPasswordButton = new JButton("Forgot Password?");
forgotPasswordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Logic for handling forgot password
// For demonstration purposes, just showing a message dialog
JOptionPane.showMessageDialog(contentPane, "Please contact administrator for password reset.");
}
});
forgotPasswordButton.setBounds(115, 275, 150, 30);
contentPane.add(forgotPasswordButton);
JButton createAccountButton = new JButton("Create New Account");
createAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Open registration form
signup registrationForm = new signup();
registrationForm.setVisible(true);
// Hide the current login frame
setVisible(false);
}
});
createAccountButton.setBounds(88, 320, 212, 39);
contentPane.add(createAccountButton);
}
}
|
210091_6 | package com.customify.client.services;
import com.customify.client.Colors;
import com.customify.client.Keys;
import com.customify.client.SendToServer;
import com.customify.client.data_format.*;
//import com.customify.client.data_format.customer.CreateCustomerFormat;
import com.customify.client.data_format.products.ProductFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
public class CustomerService {
private Socket socket;
private ObjectMapper objectMapper;
public CustomerService() {
}
public CustomerService(Socket socket) {
this.socket = socket;
}
public void create(CreateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleCreateCustomerResponse();
}
}
/**
* @author SAMUEL Dushimimana
* @role this function is to handle response on the successfully registration of the customer
*/
public void handleCreateCustomerResponse() throws IOException, ClassNotFoundException {
try {
InputStream inputStream = this.socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
List<String> response = (List<String>) objectInputStream.readObject();
String json_response = response.get(0);
System.out.println("HERE'S THE RESPONSE FROM THE SERVER => " + json_response);
} catch (Exception e) {
System.out.println("RESPONSE ERROR =>" + e.getMessage());
}
}
public Socket getSocket() {
return socket;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void handleUpdateCustomerSuccess() throws IOException, ClassNotFoundException {
InputStream inputStream = this.getSocket().getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// InputStream inputStream = this.getSocket().getInputStream();
// ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// try {
// List<Response> response = (List<Response>) objectInputStream.readObject();
// System.out.println("Status: "+ response.get(0).getStatusCode());
// if(response.get(0).getStatusCode() == 200){
// UpdateCustomerFormat updatedCustomer = (UpdateCustomerFormat) response.get(0).getData();
//
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// System.out.println("\t\t Customer Updated successfully");
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// }
// else if(response.get(0).getStatusCode() == 400){
// System.out.println("\n\nInvalid Customer format.Please enter Customer details as required\n\n");
// }
// else{
// System.out.println("\n\nUnknown error occurred.\n");
// }
//
// } catch (IOException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// } catch (ClassNotFoundException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// }
return;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void update(UpdateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleUpdateCustomerSuccess();
} else {
System.out.println("\n\nError occurred when trying to send request to server\n");
}
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully disabled customer
*/
public void disable(String json) throws IOException, ClassNotFoundException {
try {
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List) objectInput.readObject();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY DE-ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 444) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t NO RESPONSE");
System.out.println(Colors.ANSI_RESET);
}
else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t UNKNOWN CODE");
System.out.println(Colors.ANSI_RESET);
}
}
} catch (Exception e) {
System.out.println("Exception Caught ");
}
return;
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully activated customer
*/
public Object reEnableCard(String code) throws IOException, ClassNotFoundException {
DeActivateCustomer format = new DeActivateCustomer(code);
ObjectMapper objectMapper = new ObjectMapper();
String request = objectMapper.writeValueAsString(format);
SendToServer sendToServer = new SendToServer(request, socket);
if (sendToServer.send()) {
// System.out.println("\t\tCard was activated successfully\n");
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List<String>) objectInput.readObject();
String responseData = res.get(0);
// System.out.println("Response: " + responseData);
JsonNode jsonNode = new ObjectMapper().readTree(responseData);
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 400) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 500) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t SYSTEM ERROR OCCURRED");
System.out.println(Colors.ANSI_RESET);
} else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t UNKNOWN ERROR");
System.out.println(Colors.ANSI_RESET);
}
}
return null;
}
public List getAll() throws IOException {
String json = "{ \"key\" : \"" + Keys.GET_ALL_CUSTOMERS + "\"}";
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 500) {
System.out.println("\t\t\t\t---- INTERNAL SERVER ERROR -----");
return null;
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println("\n\t\t\t*******************************************************************************************************");
System.out.println(" NO CUSTOMERS FOUND ");
System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR" + e.getMessage());
}
}
return res;
}
public List get(GetCustomer format) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 404) {
// System.out.println("\n\t\t\t*******************************************************************************************************");
// System.out.println(" NO CUSTOMER FOUND ");
// System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR HERE" + e.getMessage());
}
}
return res;
}
} | customify/customify-cli | src/com/customify/client/services/CustomerService.java | 2,693 | // if(response.get(0).getStatusCode() == 200){ | line_comment | nl | package com.customify.client.services;
import com.customify.client.Colors;
import com.customify.client.Keys;
import com.customify.client.SendToServer;
import com.customify.client.data_format.*;
//import com.customify.client.data_format.customer.CreateCustomerFormat;
import com.customify.client.data_format.products.ProductFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
public class CustomerService {
private Socket socket;
private ObjectMapper objectMapper;
public CustomerService() {
}
public CustomerService(Socket socket) {
this.socket = socket;
}
public void create(CreateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleCreateCustomerResponse();
}
}
/**
* @author SAMUEL Dushimimana
* @role this function is to handle response on the successfully registration of the customer
*/
public void handleCreateCustomerResponse() throws IOException, ClassNotFoundException {
try {
InputStream inputStream = this.socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
List<String> response = (List<String>) objectInputStream.readObject();
String json_response = response.get(0);
System.out.println("HERE'S THE RESPONSE FROM THE SERVER => " + json_response);
} catch (Exception e) {
System.out.println("RESPONSE ERROR =>" + e.getMessage());
}
}
public Socket getSocket() {
return socket;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void handleUpdateCustomerSuccess() throws IOException, ClassNotFoundException {
InputStream inputStream = this.getSocket().getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// InputStream inputStream = this.getSocket().getInputStream();
// ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// try {
// List<Response> response = (List<Response>) objectInputStream.readObject();
// System.out.println("Status: "+ response.get(0).getStatusCode());
// if(response.get(0).getStatusCode() ==<SUF>
// UpdateCustomerFormat updatedCustomer = (UpdateCustomerFormat) response.get(0).getData();
//
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// System.out.println("\t\t Customer Updated successfully");
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// }
// else if(response.get(0).getStatusCode() == 400){
// System.out.println("\n\nInvalid Customer format.Please enter Customer details as required\n\n");
// }
// else{
// System.out.println("\n\nUnknown error occurred.\n");
// }
//
// } catch (IOException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// } catch (ClassNotFoundException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// }
return;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void update(UpdateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleUpdateCustomerSuccess();
} else {
System.out.println("\n\nError occurred when trying to send request to server\n");
}
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully disabled customer
*/
public void disable(String json) throws IOException, ClassNotFoundException {
try {
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List) objectInput.readObject();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY DE-ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 444) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t NO RESPONSE");
System.out.println(Colors.ANSI_RESET);
}
else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t UNKNOWN CODE");
System.out.println(Colors.ANSI_RESET);
}
}
} catch (Exception e) {
System.out.println("Exception Caught ");
}
return;
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully activated customer
*/
public Object reEnableCard(String code) throws IOException, ClassNotFoundException {
DeActivateCustomer format = new DeActivateCustomer(code);
ObjectMapper objectMapper = new ObjectMapper();
String request = objectMapper.writeValueAsString(format);
SendToServer sendToServer = new SendToServer(request, socket);
if (sendToServer.send()) {
// System.out.println("\t\tCard was activated successfully\n");
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List<String>) objectInput.readObject();
String responseData = res.get(0);
// System.out.println("Response: " + responseData);
JsonNode jsonNode = new ObjectMapper().readTree(responseData);
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 400) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 500) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t SYSTEM ERROR OCCURRED");
System.out.println(Colors.ANSI_RESET);
} else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t UNKNOWN ERROR");
System.out.println(Colors.ANSI_RESET);
}
}
return null;
}
public List getAll() throws IOException {
String json = "{ \"key\" : \"" + Keys.GET_ALL_CUSTOMERS + "\"}";
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 500) {
System.out.println("\t\t\t\t---- INTERNAL SERVER ERROR -----");
return null;
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println("\n\t\t\t*******************************************************************************************************");
System.out.println(" NO CUSTOMERS FOUND ");
System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR" + e.getMessage());
}
}
return res;
}
public List get(GetCustomer format) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 404) {
// System.out.println("\n\t\t\t*******************************************************************************************************");
// System.out.println(" NO CUSTOMER FOUND ");
// System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR HERE" + e.getMessage());
}
}
return res;
}
} |
210091_9 | package com.customify.client.services;
import com.customify.client.Colors;
import com.customify.client.Keys;
import com.customify.client.SendToServer;
import com.customify.client.data_format.*;
//import com.customify.client.data_format.customer.CreateCustomerFormat;
import com.customify.client.data_format.products.ProductFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
public class CustomerService {
private Socket socket;
private ObjectMapper objectMapper;
public CustomerService() {
}
public CustomerService(Socket socket) {
this.socket = socket;
}
public void create(CreateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleCreateCustomerResponse();
}
}
/**
* @author SAMUEL Dushimimana
* @role this function is to handle response on the successfully registration of the customer
*/
public void handleCreateCustomerResponse() throws IOException, ClassNotFoundException {
try {
InputStream inputStream = this.socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
List<String> response = (List<String>) objectInputStream.readObject();
String json_response = response.get(0);
System.out.println("HERE'S THE RESPONSE FROM THE SERVER => " + json_response);
} catch (Exception e) {
System.out.println("RESPONSE ERROR =>" + e.getMessage());
}
}
public Socket getSocket() {
return socket;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void handleUpdateCustomerSuccess() throws IOException, ClassNotFoundException {
InputStream inputStream = this.getSocket().getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// InputStream inputStream = this.getSocket().getInputStream();
// ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// try {
// List<Response> response = (List<Response>) objectInputStream.readObject();
// System.out.println("Status: "+ response.get(0).getStatusCode());
// if(response.get(0).getStatusCode() == 200){
// UpdateCustomerFormat updatedCustomer = (UpdateCustomerFormat) response.get(0).getData();
//
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// System.out.println("\t\t Customer Updated successfully");
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// }
// else if(response.get(0).getStatusCode() == 400){
// System.out.println("\n\nInvalid Customer format.Please enter Customer details as required\n\n");
// }
// else{
// System.out.println("\n\nUnknown error occurred.\n");
// }
//
// } catch (IOException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// } catch (ClassNotFoundException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// }
return;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void update(UpdateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleUpdateCustomerSuccess();
} else {
System.out.println("\n\nError occurred when trying to send request to server\n");
}
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully disabled customer
*/
public void disable(String json) throws IOException, ClassNotFoundException {
try {
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List) objectInput.readObject();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY DE-ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 444) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t NO RESPONSE");
System.out.println(Colors.ANSI_RESET);
}
else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t UNKNOWN CODE");
System.out.println(Colors.ANSI_RESET);
}
}
} catch (Exception e) {
System.out.println("Exception Caught ");
}
return;
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully activated customer
*/
public Object reEnableCard(String code) throws IOException, ClassNotFoundException {
DeActivateCustomer format = new DeActivateCustomer(code);
ObjectMapper objectMapper = new ObjectMapper();
String request = objectMapper.writeValueAsString(format);
SendToServer sendToServer = new SendToServer(request, socket);
if (sendToServer.send()) {
// System.out.println("\t\tCard was activated successfully\n");
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List<String>) objectInput.readObject();
String responseData = res.get(0);
// System.out.println("Response: " + responseData);
JsonNode jsonNode = new ObjectMapper().readTree(responseData);
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 400) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 500) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t SYSTEM ERROR OCCURRED");
System.out.println(Colors.ANSI_RESET);
} else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t UNKNOWN ERROR");
System.out.println(Colors.ANSI_RESET);
}
}
return null;
}
public List getAll() throws IOException {
String json = "{ \"key\" : \"" + Keys.GET_ALL_CUSTOMERS + "\"}";
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 500) {
System.out.println("\t\t\t\t---- INTERNAL SERVER ERROR -----");
return null;
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println("\n\t\t\t*******************************************************************************************************");
System.out.println(" NO CUSTOMERS FOUND ");
System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR" + e.getMessage());
}
}
return res;
}
public List get(GetCustomer format) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 404) {
// System.out.println("\n\t\t\t*******************************************************************************************************");
// System.out.println(" NO CUSTOMER FOUND ");
// System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR HERE" + e.getMessage());
}
}
return res;
}
} | customify/customify-cli | src/com/customify/client/services/CustomerService.java | 2,693 | // else if(response.get(0).getStatusCode() == 400){ | line_comment | nl | package com.customify.client.services;
import com.customify.client.Colors;
import com.customify.client.Keys;
import com.customify.client.SendToServer;
import com.customify.client.data_format.*;
//import com.customify.client.data_format.customer.CreateCustomerFormat;
import com.customify.client.data_format.products.ProductFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
public class CustomerService {
private Socket socket;
private ObjectMapper objectMapper;
public CustomerService() {
}
public CustomerService(Socket socket) {
this.socket = socket;
}
public void create(CreateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleCreateCustomerResponse();
}
}
/**
* @author SAMUEL Dushimimana
* @role this function is to handle response on the successfully registration of the customer
*/
public void handleCreateCustomerResponse() throws IOException, ClassNotFoundException {
try {
InputStream inputStream = this.socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
List<String> response = (List<String>) objectInputStream.readObject();
String json_response = response.get(0);
System.out.println("HERE'S THE RESPONSE FROM THE SERVER => " + json_response);
} catch (Exception e) {
System.out.println("RESPONSE ERROR =>" + e.getMessage());
}
}
public Socket getSocket() {
return socket;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void handleUpdateCustomerSuccess() throws IOException, ClassNotFoundException {
InputStream inputStream = this.getSocket().getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// InputStream inputStream = this.getSocket().getInputStream();
// ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// try {
// List<Response> response = (List<Response>) objectInputStream.readObject();
// System.out.println("Status: "+ response.get(0).getStatusCode());
// if(response.get(0).getStatusCode() == 200){
// UpdateCustomerFormat updatedCustomer = (UpdateCustomerFormat) response.get(0).getData();
//
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// System.out.println("\t\t Customer Updated successfully");
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
// }
// else if(response.get(0).getStatusCode()<SUF>
// System.out.println("\n\nInvalid Customer format.Please enter Customer details as required\n\n");
// }
// else{
// System.out.println("\n\nUnknown error occurred.\n");
// }
//
// } catch (IOException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// } catch (ClassNotFoundException e) {
// System.out.println("\n\nError occurred:" +e.getMessage()+ "\n\n");
// }
return;
}
/**
* @author Nshimiye Emmy
* @role this service method is to update the customer on client side
*/
public void update(UpdateCustomerFormat format) throws IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
this.handleUpdateCustomerSuccess();
} else {
System.out.println("\n\nError occurred when trying to send request to server\n");
}
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully disabled customer
*/
public void disable(String json) throws IOException, ClassNotFoundException {
try {
SendToServer serverSend = new SendToServer(json, this.socket);
if (serverSend.send()) {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List) objectInput.readObject();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY DE-ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 444) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t NO RESPONSE");
System.out.println(Colors.ANSI_RESET);
}
else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t UNKNOWN CODE");
System.out.println(Colors.ANSI_RESET);
}
}
} catch (Exception e) {
System.out.println("Exception Caught ");
}
return;
}
/**
* @author Murenzi Confiance Tracy
* @role this function is to handle response on the successfully activated customer
*/
public Object reEnableCard(String code) throws IOException, ClassNotFoundException {
DeActivateCustomer format = new DeActivateCustomer(code);
ObjectMapper objectMapper = new ObjectMapper();
String request = objectMapper.writeValueAsString(format);
SendToServer sendToServer = new SendToServer(request, socket);
if (sendToServer.send()) {
// System.out.println("\t\tCard was activated successfully\n");
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
List<String> res = (List<String>) objectInput.readObject();
String responseData = res.get(0);
// System.out.println("Response: " + responseData);
JsonNode jsonNode = new ObjectMapper().readTree(responseData);
if (jsonNode.get("status").asInt() == 200) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t CARD WAS SUCCESSFULLY ACTIVATED!!!!");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 400) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t THE CUSTOMER DOESN'T EXIST");
System.out.println(Colors.ANSI_RESET);
} else if (jsonNode.get("status").asInt() == 500) {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t SYSTEM ERROR OCCURRED");
System.out.println(Colors.ANSI_RESET);
} else {
System.out.println(Colors.ANSI_PURPLE);
System.out.println("\t\t\t\t\t\t\t\t\t\t UNKNOWN ERROR");
System.out.println(Colors.ANSI_RESET);
}
}
return null;
}
public List getAll() throws IOException {
String json = "{ \"key\" : \"" + Keys.GET_ALL_CUSTOMERS + "\"}";
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 500) {
System.out.println("\t\t\t\t---- INTERNAL SERVER ERROR -----");
return null;
} else if (jsonNode.get("status").asInt() == 404) {
System.out.println("\n\t\t\t*******************************************************************************************************");
System.out.println(" NO CUSTOMERS FOUND ");
System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR" + e.getMessage());
}
}
return res;
}
public List get(GetCustomer format) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(format);
SendToServer serverSend = new SendToServer(json, this.socket);
List<String> res = new ArrayList<>();
if (serverSend.send()) {
try {
InputStream input = this.socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(input);
res = (List) objectInput.readObject();
JsonNode jsonNode = objectMapper.readTree(res.get(0));
if (jsonNode.get("status").asInt() == 404) {
// System.out.println("\n\t\t\t*******************************************************************************************************");
// System.out.println(" NO CUSTOMER FOUND ");
// System.out.println("\t\t\t*******************************************************************************************************");
return null;
}
} catch (Exception e) {
System.out.println("RESPONSE ERROR HERE" + e.getMessage());
}
}
return res;
}
} |
210120_0 | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
// niet elke keer heen en weer hoeft te switchen.
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/module-krd/src/main/java/nl/topicus/eduarte/krd/web/pages/deelnemer/examens/DeelnemerKwalificatieSelecterenPage.java | 1,718 | /**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/ | block_comment | nl | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor<SUF>*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
// niet elke keer heen en weer hoeft te switchen.
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
|
210120_1 | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
// niet elke keer heen en weer hoeft te switchen.
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/module-krd/src/main/java/nl/topicus/eduarte/krd/web/pages/deelnemer/examens/DeelnemerKwalificatieSelecterenPage.java | 1,718 | // Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
| line_comment | nl | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken<SUF>
// niet elke keer heen en weer hoeft te switchen.
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
|
210120_2 | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
// niet elke keer heen en weer hoeft te switchen.
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/module-krd/src/main/java/nl/topicus/eduarte/krd/web/pages/deelnemer/examens/DeelnemerKwalificatieSelecterenPage.java | 1,718 | // niet elke keer heen en weer hoeft te switchen.
| line_comment | nl | package nl.topicus.eduarte.krd.web.pages.deelnemer.examens;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.dao.helpers.DatabaseSelection;
import nl.topicus.cobra.dao.hibernate.HibernateSelection;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.util.ComponentUtil;
import nl.topicus.cobra.web.components.Selection;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanel;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.cobra.web.components.datapanel.selection.AbstractSelectiePanel;
import nl.topicus.cobra.web.pages.IEditPage;
import nl.topicus.eduarte.app.EduArteSession;
import nl.topicus.eduarte.entities.examen.ToegestaneExamenstatusOvergang;
import nl.topicus.eduarte.entities.inschrijving.Verbintenis;
import nl.topicus.eduarte.krd.principals.deelnemer.examen.DeelnemerExamensCollectief;
import nl.topicus.eduarte.krd.web.components.panels.datapanel.columns.ExamennummerColumn;
import nl.topicus.eduarte.web.components.menu.DeelnemerCollectiefMenuItem;
import nl.topicus.eduarte.web.components.panels.datapanel.selectie.DeelnemerCohortSelectiePanel;
import nl.topicus.eduarte.web.components.panels.filter.DeelnemerCohortExamenstatusSelectieZoekFilterPanel;
import nl.topicus.eduarte.web.pages.shared.AbstractDeelnemerSelectiePage;
import nl.topicus.eduarte.web.pages.shared.DeelnemerCollectiefPageContext;
import nl.topicus.eduarte.zoekfilters.VerbintenisZoekFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* Selectie pagina voor Deelnemers.
*
* @author vandekamp
*/
@PageInfo(title = "Deelnemer(s) selecteren", menu = "Deelnemer -> Examen -> Acties-overzicht -> [Actie]")
@InPrincipal(DeelnemerExamensCollectief.class)
public class DeelnemerKwalificatieSelecterenPage extends AbstractDeelnemerSelectiePage<Verbintenis>
implements IEditPage
{
private static final long serialVersionUID = 1L;
private KwalificatieModel kwalificatieModel;
private static final VerbintenisZoekFilter getDefaultFilter(KwalificatieModel kwalificatieModel)
{
VerbintenisZoekFilter filter = new VerbintenisZoekFilter();
// Model gebruiken zodat dit tijdens de sessie onthouden wordt, en de gebruiker
// niet elke<SUF>
filter.setCohortModel(EduArteSession.get().getSelectedCohortModel());
filter.setToegestaneExamenstatusOvergang(kwalificatieModel
.getToegestaneExamenstatusOvergang());
filter.setTijdvak(kwalificatieModel.getTijdvak());
filter.addOrderByProperty("deelnemer.deelnemernummer");
filter.addOrderByProperty("persoon.roepnaam");
filter.addOrderByProperty("persoon.achternaam");
ToegestaneExamenstatusOvergang overgang =
kwalificatieModel.getToegestaneExamenstatusOvergang();
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isGeslaagd()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigGeslaagdStatus());
}
if (kwalificatieModel.getGeselecteerdeStatus() != null
&& kwalificatieModel.getGeselecteerdeStatus().isAfgewezen()
&& overgang.isBepaaltDatumUitslag())
{
filter.setExamenstatus(overgang.getExamenWorkflow().getVoorlopigAfgewezenStatus());
}
return filter;
}
public DeelnemerKwalificatieSelecterenPage(KwalificatieModel kwalifiModel)
{
this(getDefaultFilter(kwalifiModel), kwalifiModel);
}
private DeelnemerKwalificatieSelecterenPage(VerbintenisZoekFilter filter,
KwalificatieModel kwalifiModel)
{
super(DeelnemerKwalificatiePage.class, new DeelnemerCollectiefPageContext(
"Kwalificatie selecteren", DeelnemerCollectiefMenuItem.ActieOverzicht), filter,
new HibernateSelection<Verbintenis>(Verbintenis.class),
new DeelnemerKwalificatieSelecterenTarget(kwalifiModel));
this.kwalificatieModel = kwalifiModel;
}
@Override
protected AbstractSelectiePanel<Verbintenis, Verbintenis, VerbintenisZoekFilter> createSelectiePanel(
String id, VerbintenisZoekFilter filter, Selection<Verbintenis, Verbintenis> selection)
{
DeelnemerCohortSelectiePanel<Verbintenis> ret =
new DeelnemerCohortSelectiePanel<Verbintenis>(id, filter,
(DatabaseSelection<Verbintenis, Verbintenis>) selection, false)
{
private static final long serialVersionUID = 1L;
@Override
protected Panel createZoekFilterPanel(String filterPanelId,
VerbintenisZoekFilter fltr, CustomDataPanel<Verbintenis> customDataPanel)
{
return new DeelnemerCohortExamenstatusSelectieZoekFilterPanel(filterPanelId,
fltr, customDataPanel, false, kwalificatieModel
.getToegestaneExamenstatusOvergang().getExamenWorkflow());
}
};
ret.getContentDescription().addColumn(
new ExamennummerColumn("Examennummer", "Examennummer"));
CustomPropertyColumn<Verbintenis> col =
(CustomPropertyColumn<Verbintenis>) ret.getContentDescription().getColumn(
"Examenstatus");
col.setDefaultVisible(true);
return ret;
}
@Override
public int getMaxResults()
{
return Integer.MAX_VALUE;
}
@Override
public Label createTitle(String id)
{
if (kwalificatieModel.getGeselecteerdeStatus() != null)
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie()
+ ": " + kwalificatieModel.getGeselecteerdeStatus().getNaam());
return new Label(id, kwalificatieModel.getToegestaneExamenstatusOvergang().getActie());
}
@Override
protected void onDetach()
{
ComponentUtil.detachQuietly(kwalificatieModel);
super.onDetach();
}
}
|
210131_0 | package com.minegusta.janie177.wezens.types;
import com.minegusta.janie177.util.Location;
import com.minegusta.janie177.util.Velocity;
import com.minegusta.janie177.wezens.collision.CollisionAction;
import java.awt.*;
public abstract class LivingObject extends Object
{
private int health;
public LivingObject(String imagePath, int frames, int distanceBetweenFrames, int scale, boolean hasCollision, Location origin, int damage, boolean showName, String name, CollisionAction action, double bounceSpeed, int health) {
super(imagePath, frames, distanceBetweenFrames, scale, hasCollision, origin, damage, showName, name, action, bounceSpeed);
this.health = health;
}
public void animate(Graphics2D g2d, boolean flip)
{
updateLocation();
super.animate(g2d, flip);
}
public void updateLocation()
{
getLocation().setX(getLocation().getX() + getVelocity().getX()).setY(getLocation().getY() + getVelocity().getY());
getVelocity().update();
}
public void deathAnimation(Graphics2D g2d)
{
//Maak hier de animatie als een entity dood gaat.
}
public int getHealth()
{
return health;
}
public void setHealth(int health)
{
this.health = health;
}
public boolean isDead()
{
return health <= 0;
}
} | janie177/SuperDuperPlatformerSimulator2014 | src/java/com/minegusta/janie177/wezens/types/LivingObject.java | 376 | //Maak hier de animatie als een entity dood gaat. | line_comment | nl | package com.minegusta.janie177.wezens.types;
import com.minegusta.janie177.util.Location;
import com.minegusta.janie177.util.Velocity;
import com.minegusta.janie177.wezens.collision.CollisionAction;
import java.awt.*;
public abstract class LivingObject extends Object
{
private int health;
public LivingObject(String imagePath, int frames, int distanceBetweenFrames, int scale, boolean hasCollision, Location origin, int damage, boolean showName, String name, CollisionAction action, double bounceSpeed, int health) {
super(imagePath, frames, distanceBetweenFrames, scale, hasCollision, origin, damage, showName, name, action, bounceSpeed);
this.health = health;
}
public void animate(Graphics2D g2d, boolean flip)
{
updateLocation();
super.animate(g2d, flip);
}
public void updateLocation()
{
getLocation().setX(getLocation().getX() + getVelocity().getX()).setY(getLocation().getY() + getVelocity().getY());
getVelocity().update();
}
public void deathAnimation(Graphics2D g2d)
{
//Maak hier<SUF>
}
public int getHealth()
{
return health;
}
public void setHealth(int health)
{
this.health = health;
}
public boolean isDead()
{
return health <= 0;
}
} |
210154_20 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // is an independent random gaussian | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an<SUF>
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_32 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and N-1 | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i<SUF>
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_34 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and N-1 | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i<SUF>
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_36 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and N-1 | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i<SUF>
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_38 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and hi | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i<SUF>
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_40 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and hi | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i<SUF>
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210154_42 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,042 | // between i and hi | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i<SUF>
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
210229_14 | package hex.tree;
import water.util.ArrayUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Implements a method for finding new histogram bins split-points based on a result of previous binning.
* Idea:
* We take non-empty bins and look at the squared error they have. Based on the target bin number, we discard
* the empty bins and used the frees-up space to refine the non-non empty bins. Splitting of non-empty bins
* is guided by Squared Error accumulated in the bin. Bins with higher SE are split more than the bins with lower SE.
* Sub-bins (bins created from a single original bin) are refined uniformly.
*
* If uniform splitting fails in this iteration (= the distribution of values is significantly skewed), next iteration
* will attempt correct the issue by repeating the procedure with new bins (we are recursively refining the promising
* bins as we get deeper in the tree).
*/
public class GuidedSplitPoints {
static final double LOW_DENSITY_THRESHOLD = 0.2;
static boolean isApplicableTo(DHistogram h) {
return h._vals != null && // observations were not yet binned, we don't have the data to guide the splitting
h._isInt != 2 && // categorical columns have a specific handing
!h._intOpt; // integer optimized columns have a single value per bin, no point in refining such bins
}
static double[] makeSplitPoints(DHistogram h, final int targetNBins, final double min, final double maxEx) {
// Collect bins to consider for refining
final List<BinDescriptor> bins = extractNonEmptyBins(h);
// Budget is given by target number of bins in the new layer, we keep all non-empty bins
final int totalBudget = targetNBins - bins.size() - 2; // how many bins we have to allocate (save 2 spots for min/max)
if (bins.isEmpty() || totalBudget <= 0)
return null;
int budgetLeft = totalBudget; // how many bins do we have left to redistribute
double totalSE = 0;
for (BinDescriptor bin : bins) {
totalSE += bin._se;
}
// For each bin find out how many new bins we can split it into
int[] newBinCounts = new int[bins.size()];
Collections.sort(bins); // sort by SE descending
for (int b = 0; budgetLeft > 0 && b < newBinCounts.length; b++) {
BinDescriptor bin = bins.get(b);
// distributed budget proportionally to SE
int newBins = Math.min((int) Math.ceil(totalBudget * bin._se / totalSE), budgetLeft);
budgetLeft -= newBins;
newBinCounts[b] = newBins;
}
// Define new split-points
final double[] customSplitPoints = new double[targetNBins - budgetLeft];
int i = 0;
for (int b = 0; b < newBinCounts.length; b++) {
BinDescriptor bin = bins.get(b);
customSplitPoints[i++] = bin._start;
double stepSize = (bin._end - bin._start) / (1 + newBinCounts[b]);
for (int s = 0; s < newBinCounts[b]; s++) {
customSplitPoints[i] = customSplitPoints[i - 1] + stepSize;
i++;
}
}
customSplitPoints[i++] = min; // This is based on QuantilesGlobal - DHistogram has assumption min/max will be in the split-points
customSplitPoints[i++] = h._maxIn;
assert i == customSplitPoints.length;
Arrays.sort(customSplitPoints);
return ArrayUtils.makeUniqueAndLimitToRange(customSplitPoints, min, maxEx);
}
static List<BinDescriptor> extractNonEmptyBins(DHistogram h) {
final int nonEmptyBins = h.nonEmptyBins();
final List<BinDescriptor> bins = new ArrayList<>(nonEmptyBins);
for (int i = 0; i < h.nbins(); i++) {
double weight = h.w(i);
if (weight > 0) {
BinDescriptor bin = BinDescriptor.fromBin(h, i);
bins.add(bin);
}
}
return bins;
}
static class BinDescriptor implements Comparable<BinDescriptor> {
final double _start;
final double _end;
final double _se;
final double _weight;
public BinDescriptor(double start, double end, double se, double weight) {
_start = start;
_end = end;
_se = Math.max(se, 0); // rounding errors can cause SE to be negative
_weight = weight;
}
@Override
public int compareTo(BinDescriptor o) {
return -Double.compare(_se, o._se);
}
static BinDescriptor fromBin(DHistogram h, int i) {
double w = h.w(i);
double wY = h.wY(i);
double wYY = h.wYY(i);
double se = w != 0 ? wYY - wY * wY / w : 0;
return new BinDescriptor(h.binAt(i), h.binAt(i + 1), se, w);
}
// IntelliJ generated //
@Override
public String toString() {
return "BinDescriptor{" +
"_start=" + _start +
", _end=" + _end +
", _se=" + _se +
", _weight=" + _weight +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BinDescriptor that = (BinDescriptor) o;
if (Double.compare(that._start, _start) != 0) return false;
if (Double.compare(that._end, _end) != 0) return false;
if (Double.compare(that._se, _se) != 0) return false;
return Double.compare(that._weight, _weight) == 0;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(_start);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_end);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_se);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_weight);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
}
| h2oai/h2o-3 | h2o-algos/src/main/java/hex/tree/GuidedSplitPoints.java | 1,693 | // IntelliJ generated // | line_comment | nl | package hex.tree;
import water.util.ArrayUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Implements a method for finding new histogram bins split-points based on a result of previous binning.
* Idea:
* We take non-empty bins and look at the squared error they have. Based on the target bin number, we discard
* the empty bins and used the frees-up space to refine the non-non empty bins. Splitting of non-empty bins
* is guided by Squared Error accumulated in the bin. Bins with higher SE are split more than the bins with lower SE.
* Sub-bins (bins created from a single original bin) are refined uniformly.
*
* If uniform splitting fails in this iteration (= the distribution of values is significantly skewed), next iteration
* will attempt correct the issue by repeating the procedure with new bins (we are recursively refining the promising
* bins as we get deeper in the tree).
*/
public class GuidedSplitPoints {
static final double LOW_DENSITY_THRESHOLD = 0.2;
static boolean isApplicableTo(DHistogram h) {
return h._vals != null && // observations were not yet binned, we don't have the data to guide the splitting
h._isInt != 2 && // categorical columns have a specific handing
!h._intOpt; // integer optimized columns have a single value per bin, no point in refining such bins
}
static double[] makeSplitPoints(DHistogram h, final int targetNBins, final double min, final double maxEx) {
// Collect bins to consider for refining
final List<BinDescriptor> bins = extractNonEmptyBins(h);
// Budget is given by target number of bins in the new layer, we keep all non-empty bins
final int totalBudget = targetNBins - bins.size() - 2; // how many bins we have to allocate (save 2 spots for min/max)
if (bins.isEmpty() || totalBudget <= 0)
return null;
int budgetLeft = totalBudget; // how many bins do we have left to redistribute
double totalSE = 0;
for (BinDescriptor bin : bins) {
totalSE += bin._se;
}
// For each bin find out how many new bins we can split it into
int[] newBinCounts = new int[bins.size()];
Collections.sort(bins); // sort by SE descending
for (int b = 0; budgetLeft > 0 && b < newBinCounts.length; b++) {
BinDescriptor bin = bins.get(b);
// distributed budget proportionally to SE
int newBins = Math.min((int) Math.ceil(totalBudget * bin._se / totalSE), budgetLeft);
budgetLeft -= newBins;
newBinCounts[b] = newBins;
}
// Define new split-points
final double[] customSplitPoints = new double[targetNBins - budgetLeft];
int i = 0;
for (int b = 0; b < newBinCounts.length; b++) {
BinDescriptor bin = bins.get(b);
customSplitPoints[i++] = bin._start;
double stepSize = (bin._end - bin._start) / (1 + newBinCounts[b]);
for (int s = 0; s < newBinCounts[b]; s++) {
customSplitPoints[i] = customSplitPoints[i - 1] + stepSize;
i++;
}
}
customSplitPoints[i++] = min; // This is based on QuantilesGlobal - DHistogram has assumption min/max will be in the split-points
customSplitPoints[i++] = h._maxIn;
assert i == customSplitPoints.length;
Arrays.sort(customSplitPoints);
return ArrayUtils.makeUniqueAndLimitToRange(customSplitPoints, min, maxEx);
}
static List<BinDescriptor> extractNonEmptyBins(DHistogram h) {
final int nonEmptyBins = h.nonEmptyBins();
final List<BinDescriptor> bins = new ArrayList<>(nonEmptyBins);
for (int i = 0; i < h.nbins(); i++) {
double weight = h.w(i);
if (weight > 0) {
BinDescriptor bin = BinDescriptor.fromBin(h, i);
bins.add(bin);
}
}
return bins;
}
static class BinDescriptor implements Comparable<BinDescriptor> {
final double _start;
final double _end;
final double _se;
final double _weight;
public BinDescriptor(double start, double end, double se, double weight) {
_start = start;
_end = end;
_se = Math.max(se, 0); // rounding errors can cause SE to be negative
_weight = weight;
}
@Override
public int compareTo(BinDescriptor o) {
return -Double.compare(_se, o._se);
}
static BinDescriptor fromBin(DHistogram h, int i) {
double w = h.w(i);
double wY = h.wY(i);
double wYY = h.wYY(i);
double se = w != 0 ? wYY - wY * wY / w : 0;
return new BinDescriptor(h.binAt(i), h.binAt(i + 1), se, w);
}
// IntelliJ generated<SUF>
@Override
public String toString() {
return "BinDescriptor{" +
"_start=" + _start +
", _end=" + _end +
", _se=" + _se +
", _weight=" + _weight +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BinDescriptor that = (BinDescriptor) o;
if (Double.compare(that._start, _start) != 0) return false;
if (Double.compare(that._end, _end) != 0) return false;
if (Double.compare(that._se, _se) != 0) return false;
return Double.compare(that._weight, _weight) == 0;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(_start);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_end);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_se);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_weight);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
}
|
210235_4 | package com.unister.semweb.ned.QRToolNED.db;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.unister.semweb.ned.QRToolNED.datatypes.Candidate;
import com.unister.semweb.ned.QRToolNED.datatypes.Label;
import com.unister.semweb.ned.QRToolNED.datatypes.Text;
import com.unister.semweb.ned.QRToolNED.datatypes.TextWithLabels;
import com.unister.semweb.ned.QRToolNED.datatypes.Voting;
public class DbAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(DbAdapter.class);
public static final int ID_NOT_FOUND = -1;
public static final int NO_ENTITY = -1;
public static final int UNKNOWN_CANDIDAET = -2;
// private static final String SELECT_NEXT_TEXT_FOR_USER = "SELECT textsHavingCandidates.textID "
// + "FROM textsHavingCandidates "
// + "WHERE textsHavingCandidates.textID NOT IN ( "
// + " SELECT textHasLabel.textID "
// + " FROM voting, textHasLabel "
// + " WHERE voting.textHasLabelID=textHasLabel.textHasLabelID "
// + " AND voting.username = ?) "
// + "AND ( textsHavingCandidates.textID IN ("
// + " SELECT text.textID "
// + " FROM voting, text, textHasLabel "
// + " WHERE voting.textHasLabelID=textHasLabel.textHasLabelID "
// + " AND textHasLabel.textID=text.textID"
// + " GROUP BY text.textID "
// + " HAVING count(DISTINCT voting.username) < 5)"
// + "OR textsHavingCandidates.textID NOT IN ( "
// + " SELECT textHasLabel.textID "
// + " FROM voting JOIN textHasLabel USING (textHasLabelID)))"
// + "LIMIT 1;";
private static final String SELECT_NEXT_TEXT_FOR_USER = "SELECT text.textID "
+ "FROM text "
+ "WHERE text.textID NOT IN ( "
+ " SELECT userSawText.textID "
+ " FROM userSawText "
+ " WHERE userSawText.username = ?) "
+ "AND ( text.textID IN ("
+ " SELECT userSawText.textID "
+ " FROM userSawText "
+ " GROUP BY userSawText.textID "
+ " HAVING count(DISTINCT userSawText.username) < 5)"
+ "OR text.textID NOT IN ( "
+ " SELECT userSawText.textID "
+ " FROM userSawText))"
+ "LIMIT 1;";
private static final String SELECT_TEXT_WITH_TEXT_ID = "SELECT text.text " + "FROM text "
+ "WHERE text.textID = ?;";
private static final String SELECT_LABELS_OF_TEXT = "SELECT label.labelID, textHasLabel.textHasLabelID, textHasLabel.start, textHasLabel.end, label.label "
+ "FROM label JOIN textHasLabel USING (labelID) "
+ "WHERE textHasLabel.textID = ? "
+ "GROUP BY textHasLabel.end "
+ "HAVING min(textHasLabel.start) OR textHasLabel.start=0 "
+ "ORDER BY textHasLabel.end DESC, textHasLabel.start;";
private static final String SELECT_ALL_LABELS = "SELECT label.labelID, label.label FROM label";
private static final String SELECT_CANDIDATES_FOR_LABEL = "SELECT candidate.candidateID, candidate.url, candidate.label, candidate.abstract "
+ " FROM candidate, labelHasCandidate "
+ " WHERE candidate.candidateID = labelHasCandidate.candidateID AND labelHasCandidate.labelID = ?;";
private static final String SELECT_HIGHEST_TEXT_ID = "SELECT max(text.textID) FROM text";
private static final String SELECT_ID_OF_LABEL = "SELECT label.labelID FROM label WHERE label.label=?";
private static final String SELECT_ID_OF_CANDIDATE = "SELECT candidate.candidateID FROM candidate WHERE candidate.url=?";
private static final String SELECT_EXISTENZ_OF_LABEL_HAS_CANDIDATE_RELATION = "SELECT count(*) FROM labelHasCandidate WHERE labelHasCandidate.labelID=? AND labelHasCandidate.candidateID=?";
private static final String SELECT_IDS_OF_VOTED_TEXTS = "SELECT ust.textID FROM userSawText ust GROUP BY ust.textID HAVING Count(ust.username) >= ?";
private static final String SELECT_POSITIV_VOTED_LABELS_IN_TEXT = "SELECT v.votingID, c.candidateID, c.url, c.label, v.username FROM voting v, candidate c WHERE v.textHasLabelID=? AND v.candidateID=c.candidateID";
private static final String SELECT_VOTED_LABELS_WHICH_ARE_NO_ENTITIES = "SELECT v.votingID, v.candidateID, v.username FROM voting v WHERE v.textHasLabelID=? AND v.candidateID="
+ Candidate.NO_ENTITY_CANDIDATE_ID;
private static final String SELECT_VOTED_LABELS_WITH_UNKNOWN_CANDIDATE_IN_TEXT = "SELECT v.votingID, v.candidateID, a.anotherEntity, a.anotherEntity, v.username FROM voting v, anotherEntity a WHERE v.textHasLabelID=? AND v.candidateID="
+ Candidate.OTHER_ENTITY_CANDIDATE_ID + " AND v.textHasLabelID=a.textHasLabelID AND v.username=a.username";
private static final String SELECT_NOT_IDENTIFIED_NES_IN_TEXT = "SELECT label, start, end FROM notIdentifiedNE WHERE textID=?";
private static final String INSERT_NOT_IDENTIFIED_NE = "INSERT INTO notIdentifiedNE (textID, label, start, end) VALUES (?, ?, ?, ? )";
private static final String INSERT_VOTING = "INSERT INTO voting (textHasLabelID, username, candidateID) VALUES (?, ?, ?)";
private static final String INSERT_ANOTHER_ENTITY = "INSERT INTO anotherEntity (textHasLabelID, username, anotherEntity) VALUES (?, ?, ?)";
// private static final String INSERT_VOTING = "INSERT INTO voting (textID, username, labelID, uri) " +
// "SELECT textHasLabel.textHasLabelID, ?, ? " +
// "FROM textHasLabel " +
// "WHERE textHasLabel.textID=? " +
// "AND textHasLabel.labelID=";
private static final String INSERT_TEXT = "INSERT INTO text (textID, text) VALUES (?, ?)";
private static final String INSERT_LABEL = "INSERT INTO label (label) VALUES (?)";
private static final String INSERT_TEXT_HAS_LABEL = "INSERT INTO textHasLabel (textID, labelID, start, end) VALUES (?, ?, ?, ?)";
private static final String INSERT_CANDIDATE = "INSERT INTO candidate (url, label, abstract) VALUES (?, ?, ?)";
private static final String INSERT_LABEL_HAS_CANDIDATE = "INSERT INTO labelHasCandidate (labelID, candidateID) VALUES (?, ?)";
private static final String INSERT_USER_SAW_TEXT = "INSERT INTO userSawText (textID, username) VALUES (?, ?)";
private JdbcTemplate jdbctemplate;
public DbAdapter(ComboPooledDataSource datasource) {
this.jdbctemplate = new JdbcTemplate(datasource);
}
protected boolean doesLabelAlreadyHasCandidate(Integer labelId, Integer candidateId) {
List<Integer> candidateIds = jdbctemplate.query(SELECT_EXISTENZ_OF_LABEL_HAS_CANDIDATE_RELATION, new Object[] {
labelId, candidateId }, new IntegerRowMapper());
if (candidateIds.size() > 0) {
return candidateIds.get(0) > 0;
} else {
return false;
}
}
public List<Label> getAllLabels() {
// label.labelID, label.label
return jdbctemplate.query(SELECT_ALL_LABELS, new LabelRowMapper(2, 1, LabelRowMapper.NOT_IN_RESULT_SET,
LabelRowMapper.NOT_IN_RESULT_SET, LabelRowMapper.NOT_IN_RESULT_SET));
}
public List<Candidate> getCandidatesForLabel(Integer labelId) {
return jdbctemplate.query(SELECT_CANDIDATES_FOR_LABEL, new Object[] { labelId }, new CandidateRowMapper());
}
public int getIdOfCandidate(String url) {
List<Integer> candidateIds = jdbctemplate.query(SELECT_ID_OF_CANDIDATE, new Object[] { url },
new IntegerRowMapper());
if (candidateIds.size() > 0) {
return candidateIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public int getIdOfCandidateAndInsertIfNotExists(Candidate candidate) {
int candidateId = getIdOfCandidate(candidate.getUrl());
if (candidateId == ID_NOT_FOUND) {
insertCandidate(candidate);
candidateId = getIdOfCandidate(candidate.getUrl());
}
return candidateId;
}
public int getIdOfLabel(String label) {
List<Integer> labelIds = jdbctemplate.query(SELECT_ID_OF_LABEL, new Object[] { label }, new IntegerRowMapper());
if (labelIds.size() > 0) {
return labelIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public int getIdOfLabelAndInsertIfNotExists(String label) {
int labelId = getIdOfLabel(label);
if (labelId == ID_NOT_FOUND) {
insertLabel(label);
labelId = getIdOfLabel(label);
}
return labelId;
}
public List<Integer> getIdsOfVotedTexts() {
return getIdsOfVotedTexts(1);
}
public List<Integer> getIdsOfVotedTexts(Integer minVotingCount) {
return jdbctemplate.query(SELECT_IDS_OF_VOTED_TEXTS, new Object[] { minVotingCount }, new IntegerRowMapper());
}
public List<Label> getLabelsForText(Integer textId) {
// label.labelID, textHasLabel.textHasLabelID, textHasLabel.start, textHasLabel.end, label.label
return jdbctemplate.query(SELECT_LABELS_OF_TEXT, new Object[] { textId }, new LabelRowMapper(5, 1, 3, 4, 2));
}
private int getHighestTextId() {
List<Integer> textIds = jdbctemplate.query(SELECT_HIGHEST_TEXT_ID, new IntegerRowMapper());
if (textIds.size() > 0) {
return textIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public List<Label> getNotIdentifiedEntities(int textId) {
return jdbctemplate.query(SELECT_NOT_IDENTIFIED_NES_IN_TEXT, new Object[] { textId }, new LabelRowMapper(1,
LabelRowMapper.NOT_IN_RESULT_SET, 2, 3, LabelRowMapper.NOT_IN_RESULT_SET));
}
public TextWithLabels getTextForUser(String userName) {
Integer textId = getTextIdForUser(userName);
if (textId.intValue() == ID_NOT_FOUND) {
return null;
}
Text text = getTextWithId(textId);
if (text == null) {
return null;
}
List<Label> labels = getLabelsForText(textId);
for (Label label : labels) {
label.setCandidates(getCandidatesForLabel(label.getLabelId()));
}
return new TextWithLabels(text, labels);
}
public Integer getTextIdForUser(String userName) {
List<Integer> textIds = jdbctemplate.query(SELECT_NEXT_TEXT_FOR_USER, new Object[] { userName },
new IntegerRowMapper());
if (textIds.size() > 0) {
return textIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public Text getTextWithId(Integer textId) {
List<String> texts = jdbctemplate.query(SELECT_TEXT_WITH_TEXT_ID, new Object[] { textId },
new StringRowMapper());
if (texts.size() > 0) {
return new Text(textId, texts.get(0));
} else {
return null;
}
}
public TextWithLabels getTextWithVotings(Integer textId) {
Text text = getTextWithId(textId);
if (text == null) {
return null;
}
List<Label> labels = getLabelsForText(textId);
for (Label label : labels) {
label.setCandidates(new ArrayList<Candidate>(getVotingsForLabel(label.getTextHasLabelId())));
}
return new TextWithLabels(text, labels);
}
public List<Voting> getVotingsForLabel(Integer textHasLabelId) {
List<Voting> votings = jdbctemplate.query(SELECT_POSITIV_VOTED_LABELS_IN_TEXT, new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, 3, 4, 5));
votings.addAll(jdbctemplate.query(SELECT_VOTED_LABELS_WHICH_ARE_NO_ENTITIES, new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, VotingRowMapper.NOT_IN_RESULT_SET, VotingRowMapper.NOT_IN_RESULT_SET, 3)));
votings.addAll(jdbctemplate.query(SELECT_VOTED_LABELS_WITH_UNKNOWN_CANDIDATE_IN_TEXT,
new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, 3, 4, 5)));
return votings;
}
public void insertCandidate(Candidate candidate) {
if (jdbctemplate.update(INSERT_CANDIDATE,
new Object[] { candidate.getUrl(), candidate.getLabel(), candidate.getDescription() }) == 0) {
LOGGER.error("Insertion of a new candidate had no effect.");
return;
}
}
/**
* Inserts the given {@link Candidate} if it is not already in the database and inserts the relation to the label
* with the given labelId.
*
* @param labelId
* @param candidate
*/
public void insertCandidateOfLabel(Integer labelId, Candidate candidate) {
insertLabelHasCandidate(labelId, getIdOfCandidateAndInsertIfNotExists(candidate));
}
/**
* Inserts the given {@link Label} object, all its {@link Candidate}s and the relations between the {@link Label}
* and the {@link Candidate}s, and returns the new id of the {@link Label}.
*
* @param label
*/
public int insertLabel(final Label label) {
int labelId = getIdOfLabelAndInsertIfNotExists(label.getLabel());
for (Candidate candidate : label.getCandidates()) {
insertCandidateOfLabel(labelId, candidate);
}
return labelId;
}
public void insertLabel(String label) {
if (jdbctemplate.update(INSERT_LABEL, new Object[] { label }) == 0) {
LOGGER.error("Insertion of a new label had no effect.");
return;
}
}
/**
* Inserts the relation of the label with the given labelId and the candidate with the given candidateId into the
* database if it does not already exists.
*
* @param labelId
* @param candidateId
*/
public void insertLabelHasCandidate(Integer labelId, Integer candidateId) {
if (!doesLabelAlreadyHasCandidate(labelId, candidateId)) {
if (jdbctemplate.update(INSERT_LABEL_HAS_CANDIDATE, new Object[] { labelId, candidateId }) == 0) {
LOGGER.error("Insertion of a new labelHasCandidate relation had no effect.");
return;
}
}
}
/**
* Inserts the relation between the text with the given Id and the given label. If the label is not already in the
* database it will be inserted first.
*
* @param textId
* @param label
*/
public void insertLabelOfText(Label label, Integer textId) {
int labelId = insertLabel(label);
insertTextHasLabel(textId, labelId, label.getStart(), label.getEnd());
}
public void insertNotIdentifiedNE(Integer textId, String label, Integer start, Integer end) {
if (jdbctemplate.update(INSERT_NOT_IDENTIFIED_NE, new Object[] { textId, label, start, end }) == 0) {
LOGGER.error("Insertion of a new not identified NE had no effect.");
}
}
/**
* Inserts the given {@link Text} and returns its new Id. Note that the internal id of the {@link Text}-object is
* not used or changed.
*
* @param text
*/
public int insertText(Text text) {
int textId = getHighestTextId();
if (textId == ID_NOT_FOUND) {
textId = 0;
}
++textId;
insertText(text, textId);
return textId;
}
/**
* Inserts the given {@link Text} using the given textId. Note that the internal id of the {@link Text}-object is
* not used or changed.
*
* @param text
* @param textId
*/
public void insertText(Text text, int textId) {
if (jdbctemplate.update(INSERT_TEXT, new Object[] { textId, text.getText() }) == 0) {
LOGGER.error("Insertion of a new text had no effect.");
}
}
/**
* Inserts the relation between the text with the given Id and the given label. Note that the given label must have
* its labelId set! If this is not the case use {@link #insertLabelOfText(Label, int)} instead.
*
* @param textId
* @param label
*/
public void insertTextHasLabel(Integer textId, Label label) {
insertTextHasLabel(textId, label.getLabelId(), label.getStart(), label.getEnd());
}
/**
* Inserts the relation between the text with the given Id and the label with the given Id using the given start and
* end positions.
*
* @param textId
* @param labelId
* @param start
* @param end
*/
public void insertTextHasLabel(Integer textId, Integer labelId, Integer start, Integer end) {
if (jdbctemplate.update(INSERT_TEXT_HAS_LABEL, new Object[] { textId, labelId, start, end }) == 0) {
LOGGER.error("Insertion of a new textHasLabel relation had no effect.");
return;
}
}
/**
* Inserts the given {@link TextWithLabels}, its {@link Label}s and their {@link Candidate}s, and returns the new Id
* of the {@link TextWithLabels}.
*
* @param text
*/
public int insertTextWithLabels(final TextWithLabels text) {
int textId = insertText(text);
if (textId != ID_NOT_FOUND) {
for (Label label : text.getLabels()) {
insertLabelOfText(label, textId);
}
}
return textId;
}
public int insertTextWithLabels(final TextWithLabels text, int textId) {
insertText(text, textId);
if (textId != ID_NOT_FOUND) {
for (Label label : text.getLabels()) {
insertLabelOfText(label, textId);
}
}
return textId;
}
public void insertUserSawText(final String user, final Integer textId) {
if (jdbctemplate.update(INSERT_USER_SAW_TEXT, new Object[] { textId, user }) == 0) {
LOGGER.error("Insertion of a new textHasLabel relation had no effect.");
return;
}
}
public void insertVoting(Integer textHasLabelId, String username, Integer candidateId) {
if (jdbctemplate.update(INSERT_VOTING, new Object[] { textHasLabelId, username, candidateId }) == 0) {
LOGGER.error("Insertion of a new voting had no effect.");
}
}
/**
* Sets the Id of the the given {@link Candidate} to the Id inside the database. If this {@link Candidate} is not
* already in the database it will be inserted.
*
* @param candidate
*/
public void setIdOfCandidateAndInsertIfNotExists(Candidate candidate) {
candidate.setId(getIdOfCandidateAndInsertIfNotExists(candidate));
}
/**
* Sets the Id of the the given {@link Label} to the Id inside the database. If this {@link Label} is not already in
* the database it will be inserted.
*
* @param label
*/
public void setIdOfLabelAndInsertIfNotExists(Label label) {
label.setLabelId(getIdOfLabelAndInsertIfNotExists(label.getLabel()));
}
public void insertAnotherEntity(Integer textHasLabelId, String userName, String anotherEntity) {
if (jdbctemplate.update(INSERT_ANOTHER_ENTITY, new Object[] { textHasLabelId, userName, anotherEntity }) == 0) {
LOGGER.error("Insertion of a new voting had no effect.");
}
}
}
| dice-group/QRTool | src/main/java/com/unister/semweb/ned/QRToolNED/db/DbAdapter.java | 5,349 | // + " FROM voting, textHasLabel " | line_comment | nl | package com.unister.semweb.ned.QRToolNED.db;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.unister.semweb.ned.QRToolNED.datatypes.Candidate;
import com.unister.semweb.ned.QRToolNED.datatypes.Label;
import com.unister.semweb.ned.QRToolNED.datatypes.Text;
import com.unister.semweb.ned.QRToolNED.datatypes.TextWithLabels;
import com.unister.semweb.ned.QRToolNED.datatypes.Voting;
public class DbAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(DbAdapter.class);
public static final int ID_NOT_FOUND = -1;
public static final int NO_ENTITY = -1;
public static final int UNKNOWN_CANDIDAET = -2;
// private static final String SELECT_NEXT_TEXT_FOR_USER = "SELECT textsHavingCandidates.textID "
// + "FROM textsHavingCandidates "
// + "WHERE textsHavingCandidates.textID NOT IN ( "
// + " SELECT textHasLabel.textID "
// + "<SUF>
// + " WHERE voting.textHasLabelID=textHasLabel.textHasLabelID "
// + " AND voting.username = ?) "
// + "AND ( textsHavingCandidates.textID IN ("
// + " SELECT text.textID "
// + " FROM voting, text, textHasLabel "
// + " WHERE voting.textHasLabelID=textHasLabel.textHasLabelID "
// + " AND textHasLabel.textID=text.textID"
// + " GROUP BY text.textID "
// + " HAVING count(DISTINCT voting.username) < 5)"
// + "OR textsHavingCandidates.textID NOT IN ( "
// + " SELECT textHasLabel.textID "
// + " FROM voting JOIN textHasLabel USING (textHasLabelID)))"
// + "LIMIT 1;";
private static final String SELECT_NEXT_TEXT_FOR_USER = "SELECT text.textID "
+ "FROM text "
+ "WHERE text.textID NOT IN ( "
+ " SELECT userSawText.textID "
+ " FROM userSawText "
+ " WHERE userSawText.username = ?) "
+ "AND ( text.textID IN ("
+ " SELECT userSawText.textID "
+ " FROM userSawText "
+ " GROUP BY userSawText.textID "
+ " HAVING count(DISTINCT userSawText.username) < 5)"
+ "OR text.textID NOT IN ( "
+ " SELECT userSawText.textID "
+ " FROM userSawText))"
+ "LIMIT 1;";
private static final String SELECT_TEXT_WITH_TEXT_ID = "SELECT text.text " + "FROM text "
+ "WHERE text.textID = ?;";
private static final String SELECT_LABELS_OF_TEXT = "SELECT label.labelID, textHasLabel.textHasLabelID, textHasLabel.start, textHasLabel.end, label.label "
+ "FROM label JOIN textHasLabel USING (labelID) "
+ "WHERE textHasLabel.textID = ? "
+ "GROUP BY textHasLabel.end "
+ "HAVING min(textHasLabel.start) OR textHasLabel.start=0 "
+ "ORDER BY textHasLabel.end DESC, textHasLabel.start;";
private static final String SELECT_ALL_LABELS = "SELECT label.labelID, label.label FROM label";
private static final String SELECT_CANDIDATES_FOR_LABEL = "SELECT candidate.candidateID, candidate.url, candidate.label, candidate.abstract "
+ " FROM candidate, labelHasCandidate "
+ " WHERE candidate.candidateID = labelHasCandidate.candidateID AND labelHasCandidate.labelID = ?;";
private static final String SELECT_HIGHEST_TEXT_ID = "SELECT max(text.textID) FROM text";
private static final String SELECT_ID_OF_LABEL = "SELECT label.labelID FROM label WHERE label.label=?";
private static final String SELECT_ID_OF_CANDIDATE = "SELECT candidate.candidateID FROM candidate WHERE candidate.url=?";
private static final String SELECT_EXISTENZ_OF_LABEL_HAS_CANDIDATE_RELATION = "SELECT count(*) FROM labelHasCandidate WHERE labelHasCandidate.labelID=? AND labelHasCandidate.candidateID=?";
private static final String SELECT_IDS_OF_VOTED_TEXTS = "SELECT ust.textID FROM userSawText ust GROUP BY ust.textID HAVING Count(ust.username) >= ?";
private static final String SELECT_POSITIV_VOTED_LABELS_IN_TEXT = "SELECT v.votingID, c.candidateID, c.url, c.label, v.username FROM voting v, candidate c WHERE v.textHasLabelID=? AND v.candidateID=c.candidateID";
private static final String SELECT_VOTED_LABELS_WHICH_ARE_NO_ENTITIES = "SELECT v.votingID, v.candidateID, v.username FROM voting v WHERE v.textHasLabelID=? AND v.candidateID="
+ Candidate.NO_ENTITY_CANDIDATE_ID;
private static final String SELECT_VOTED_LABELS_WITH_UNKNOWN_CANDIDATE_IN_TEXT = "SELECT v.votingID, v.candidateID, a.anotherEntity, a.anotherEntity, v.username FROM voting v, anotherEntity a WHERE v.textHasLabelID=? AND v.candidateID="
+ Candidate.OTHER_ENTITY_CANDIDATE_ID + " AND v.textHasLabelID=a.textHasLabelID AND v.username=a.username";
private static final String SELECT_NOT_IDENTIFIED_NES_IN_TEXT = "SELECT label, start, end FROM notIdentifiedNE WHERE textID=?";
private static final String INSERT_NOT_IDENTIFIED_NE = "INSERT INTO notIdentifiedNE (textID, label, start, end) VALUES (?, ?, ?, ? )";
private static final String INSERT_VOTING = "INSERT INTO voting (textHasLabelID, username, candidateID) VALUES (?, ?, ?)";
private static final String INSERT_ANOTHER_ENTITY = "INSERT INTO anotherEntity (textHasLabelID, username, anotherEntity) VALUES (?, ?, ?)";
// private static final String INSERT_VOTING = "INSERT INTO voting (textID, username, labelID, uri) " +
// "SELECT textHasLabel.textHasLabelID, ?, ? " +
// "FROM textHasLabel " +
// "WHERE textHasLabel.textID=? " +
// "AND textHasLabel.labelID=";
private static final String INSERT_TEXT = "INSERT INTO text (textID, text) VALUES (?, ?)";
private static final String INSERT_LABEL = "INSERT INTO label (label) VALUES (?)";
private static final String INSERT_TEXT_HAS_LABEL = "INSERT INTO textHasLabel (textID, labelID, start, end) VALUES (?, ?, ?, ?)";
private static final String INSERT_CANDIDATE = "INSERT INTO candidate (url, label, abstract) VALUES (?, ?, ?)";
private static final String INSERT_LABEL_HAS_CANDIDATE = "INSERT INTO labelHasCandidate (labelID, candidateID) VALUES (?, ?)";
private static final String INSERT_USER_SAW_TEXT = "INSERT INTO userSawText (textID, username) VALUES (?, ?)";
private JdbcTemplate jdbctemplate;
public DbAdapter(ComboPooledDataSource datasource) {
this.jdbctemplate = new JdbcTemplate(datasource);
}
protected boolean doesLabelAlreadyHasCandidate(Integer labelId, Integer candidateId) {
List<Integer> candidateIds = jdbctemplate.query(SELECT_EXISTENZ_OF_LABEL_HAS_CANDIDATE_RELATION, new Object[] {
labelId, candidateId }, new IntegerRowMapper());
if (candidateIds.size() > 0) {
return candidateIds.get(0) > 0;
} else {
return false;
}
}
public List<Label> getAllLabels() {
// label.labelID, label.label
return jdbctemplate.query(SELECT_ALL_LABELS, new LabelRowMapper(2, 1, LabelRowMapper.NOT_IN_RESULT_SET,
LabelRowMapper.NOT_IN_RESULT_SET, LabelRowMapper.NOT_IN_RESULT_SET));
}
public List<Candidate> getCandidatesForLabel(Integer labelId) {
return jdbctemplate.query(SELECT_CANDIDATES_FOR_LABEL, new Object[] { labelId }, new CandidateRowMapper());
}
public int getIdOfCandidate(String url) {
List<Integer> candidateIds = jdbctemplate.query(SELECT_ID_OF_CANDIDATE, new Object[] { url },
new IntegerRowMapper());
if (candidateIds.size() > 0) {
return candidateIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public int getIdOfCandidateAndInsertIfNotExists(Candidate candidate) {
int candidateId = getIdOfCandidate(candidate.getUrl());
if (candidateId == ID_NOT_FOUND) {
insertCandidate(candidate);
candidateId = getIdOfCandidate(candidate.getUrl());
}
return candidateId;
}
public int getIdOfLabel(String label) {
List<Integer> labelIds = jdbctemplate.query(SELECT_ID_OF_LABEL, new Object[] { label }, new IntegerRowMapper());
if (labelIds.size() > 0) {
return labelIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public int getIdOfLabelAndInsertIfNotExists(String label) {
int labelId = getIdOfLabel(label);
if (labelId == ID_NOT_FOUND) {
insertLabel(label);
labelId = getIdOfLabel(label);
}
return labelId;
}
public List<Integer> getIdsOfVotedTexts() {
return getIdsOfVotedTexts(1);
}
public List<Integer> getIdsOfVotedTexts(Integer minVotingCount) {
return jdbctemplate.query(SELECT_IDS_OF_VOTED_TEXTS, new Object[] { minVotingCount }, new IntegerRowMapper());
}
public List<Label> getLabelsForText(Integer textId) {
// label.labelID, textHasLabel.textHasLabelID, textHasLabel.start, textHasLabel.end, label.label
return jdbctemplate.query(SELECT_LABELS_OF_TEXT, new Object[] { textId }, new LabelRowMapper(5, 1, 3, 4, 2));
}
private int getHighestTextId() {
List<Integer> textIds = jdbctemplate.query(SELECT_HIGHEST_TEXT_ID, new IntegerRowMapper());
if (textIds.size() > 0) {
return textIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public List<Label> getNotIdentifiedEntities(int textId) {
return jdbctemplate.query(SELECT_NOT_IDENTIFIED_NES_IN_TEXT, new Object[] { textId }, new LabelRowMapper(1,
LabelRowMapper.NOT_IN_RESULT_SET, 2, 3, LabelRowMapper.NOT_IN_RESULT_SET));
}
public TextWithLabels getTextForUser(String userName) {
Integer textId = getTextIdForUser(userName);
if (textId.intValue() == ID_NOT_FOUND) {
return null;
}
Text text = getTextWithId(textId);
if (text == null) {
return null;
}
List<Label> labels = getLabelsForText(textId);
for (Label label : labels) {
label.setCandidates(getCandidatesForLabel(label.getLabelId()));
}
return new TextWithLabels(text, labels);
}
public Integer getTextIdForUser(String userName) {
List<Integer> textIds = jdbctemplate.query(SELECT_NEXT_TEXT_FOR_USER, new Object[] { userName },
new IntegerRowMapper());
if (textIds.size() > 0) {
return textIds.get(0);
} else {
return ID_NOT_FOUND;
}
}
public Text getTextWithId(Integer textId) {
List<String> texts = jdbctemplate.query(SELECT_TEXT_WITH_TEXT_ID, new Object[] { textId },
new StringRowMapper());
if (texts.size() > 0) {
return new Text(textId, texts.get(0));
} else {
return null;
}
}
public TextWithLabels getTextWithVotings(Integer textId) {
Text text = getTextWithId(textId);
if (text == null) {
return null;
}
List<Label> labels = getLabelsForText(textId);
for (Label label : labels) {
label.setCandidates(new ArrayList<Candidate>(getVotingsForLabel(label.getTextHasLabelId())));
}
return new TextWithLabels(text, labels);
}
public List<Voting> getVotingsForLabel(Integer textHasLabelId) {
List<Voting> votings = jdbctemplate.query(SELECT_POSITIV_VOTED_LABELS_IN_TEXT, new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, 3, 4, 5));
votings.addAll(jdbctemplate.query(SELECT_VOTED_LABELS_WHICH_ARE_NO_ENTITIES, new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, VotingRowMapper.NOT_IN_RESULT_SET, VotingRowMapper.NOT_IN_RESULT_SET, 3)));
votings.addAll(jdbctemplate.query(SELECT_VOTED_LABELS_WITH_UNKNOWN_CANDIDATE_IN_TEXT,
new Object[] { textHasLabelId },
new VotingRowMapper(1, 2, 3, 4, 5)));
return votings;
}
public void insertCandidate(Candidate candidate) {
if (jdbctemplate.update(INSERT_CANDIDATE,
new Object[] { candidate.getUrl(), candidate.getLabel(), candidate.getDescription() }) == 0) {
LOGGER.error("Insertion of a new candidate had no effect.");
return;
}
}
/**
* Inserts the given {@link Candidate} if it is not already in the database and inserts the relation to the label
* with the given labelId.
*
* @param labelId
* @param candidate
*/
public void insertCandidateOfLabel(Integer labelId, Candidate candidate) {
insertLabelHasCandidate(labelId, getIdOfCandidateAndInsertIfNotExists(candidate));
}
/**
* Inserts the given {@link Label} object, all its {@link Candidate}s and the relations between the {@link Label}
* and the {@link Candidate}s, and returns the new id of the {@link Label}.
*
* @param label
*/
public int insertLabel(final Label label) {
int labelId = getIdOfLabelAndInsertIfNotExists(label.getLabel());
for (Candidate candidate : label.getCandidates()) {
insertCandidateOfLabel(labelId, candidate);
}
return labelId;
}
public void insertLabel(String label) {
if (jdbctemplate.update(INSERT_LABEL, new Object[] { label }) == 0) {
LOGGER.error("Insertion of a new label had no effect.");
return;
}
}
/**
* Inserts the relation of the label with the given labelId and the candidate with the given candidateId into the
* database if it does not already exists.
*
* @param labelId
* @param candidateId
*/
public void insertLabelHasCandidate(Integer labelId, Integer candidateId) {
if (!doesLabelAlreadyHasCandidate(labelId, candidateId)) {
if (jdbctemplate.update(INSERT_LABEL_HAS_CANDIDATE, new Object[] { labelId, candidateId }) == 0) {
LOGGER.error("Insertion of a new labelHasCandidate relation had no effect.");
return;
}
}
}
/**
* Inserts the relation between the text with the given Id and the given label. If the label is not already in the
* database it will be inserted first.
*
* @param textId
* @param label
*/
public void insertLabelOfText(Label label, Integer textId) {
int labelId = insertLabel(label);
insertTextHasLabel(textId, labelId, label.getStart(), label.getEnd());
}
public void insertNotIdentifiedNE(Integer textId, String label, Integer start, Integer end) {
if (jdbctemplate.update(INSERT_NOT_IDENTIFIED_NE, new Object[] { textId, label, start, end }) == 0) {
LOGGER.error("Insertion of a new not identified NE had no effect.");
}
}
/**
* Inserts the given {@link Text} and returns its new Id. Note that the internal id of the {@link Text}-object is
* not used or changed.
*
* @param text
*/
public int insertText(Text text) {
int textId = getHighestTextId();
if (textId == ID_NOT_FOUND) {
textId = 0;
}
++textId;
insertText(text, textId);
return textId;
}
/**
* Inserts the given {@link Text} using the given textId. Note that the internal id of the {@link Text}-object is
* not used or changed.
*
* @param text
* @param textId
*/
public void insertText(Text text, int textId) {
if (jdbctemplate.update(INSERT_TEXT, new Object[] { textId, text.getText() }) == 0) {
LOGGER.error("Insertion of a new text had no effect.");
}
}
/**
* Inserts the relation between the text with the given Id and the given label. Note that the given label must have
* its labelId set! If this is not the case use {@link #insertLabelOfText(Label, int)} instead.
*
* @param textId
* @param label
*/
public void insertTextHasLabel(Integer textId, Label label) {
insertTextHasLabel(textId, label.getLabelId(), label.getStart(), label.getEnd());
}
/**
* Inserts the relation between the text with the given Id and the label with the given Id using the given start and
* end positions.
*
* @param textId
* @param labelId
* @param start
* @param end
*/
public void insertTextHasLabel(Integer textId, Integer labelId, Integer start, Integer end) {
if (jdbctemplate.update(INSERT_TEXT_HAS_LABEL, new Object[] { textId, labelId, start, end }) == 0) {
LOGGER.error("Insertion of a new textHasLabel relation had no effect.");
return;
}
}
/**
* Inserts the given {@link TextWithLabels}, its {@link Label}s and their {@link Candidate}s, and returns the new Id
* of the {@link TextWithLabels}.
*
* @param text
*/
public int insertTextWithLabels(final TextWithLabels text) {
int textId = insertText(text);
if (textId != ID_NOT_FOUND) {
for (Label label : text.getLabels()) {
insertLabelOfText(label, textId);
}
}
return textId;
}
public int insertTextWithLabels(final TextWithLabels text, int textId) {
insertText(text, textId);
if (textId != ID_NOT_FOUND) {
for (Label label : text.getLabels()) {
insertLabelOfText(label, textId);
}
}
return textId;
}
public void insertUserSawText(final String user, final Integer textId) {
if (jdbctemplate.update(INSERT_USER_SAW_TEXT, new Object[] { textId, user }) == 0) {
LOGGER.error("Insertion of a new textHasLabel relation had no effect.");
return;
}
}
public void insertVoting(Integer textHasLabelId, String username, Integer candidateId) {
if (jdbctemplate.update(INSERT_VOTING, new Object[] { textHasLabelId, username, candidateId }) == 0) {
LOGGER.error("Insertion of a new voting had no effect.");
}
}
/**
* Sets the Id of the the given {@link Candidate} to the Id inside the database. If this {@link Candidate} is not
* already in the database it will be inserted.
*
* @param candidate
*/
public void setIdOfCandidateAndInsertIfNotExists(Candidate candidate) {
candidate.setId(getIdOfCandidateAndInsertIfNotExists(candidate));
}
/**
* Sets the Id of the the given {@link Label} to the Id inside the database. If this {@link Label} is not already in
* the database it will be inserted.
*
* @param label
*/
public void setIdOfLabelAndInsertIfNotExists(Label label) {
label.setLabelId(getIdOfLabelAndInsertIfNotExists(label.getLabel()));
}
public void insertAnotherEntity(Integer textHasLabelId, String userName, String anotherEntity) {
if (jdbctemplate.update(INSERT_ANOTHER_ENTITY, new Object[] { textHasLabelId, userName, anotherEntity }) == 0) {
LOGGER.error("Insertion of a new voting had no effect.");
}
}
}
|
210343_1 | package dao;
import entity.Event;
import entity.User;
import java.sql.*;
import java.util.ArrayList;
public class EventDAO extends BaseDAO {
//save event enkel met titel
public void saveEvent(Event event)
{
try(Connection conn = getConn()){
PreparedStatement stmt = conn.prepareStatement("INSERT INTO evenementen (titel) VALUES (?)");
stmt.setString(1, event.getTitle());
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
//save event met meer velden
public void saveEventMoreFields(Event event){
Connection conn = null;
try {
conn = getConn();
} catch (Exception e) {
e.printStackTrace();
}
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO evenementen (evenementid, titel, datum, organisator, bier) VALUES (NULL, ?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) {
ps.setString(2, event.getTitle());
ps.setDate(3, Date.valueOf(event.getEventDate()));
ps.setString(4, String.valueOf(event.getOrganisingBrewery()));
ps.setString(5, String.valueOf(event.getFeaturedBeer()));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
//?
try (PreparedStatement ps2 = conn.prepareStatement("INSERT INTO aanwezigen (evenementid, gebruikersid) VALUES (NULL, ?)", Statement.RETURN_GENERATED_KEYS)) {
for (User v : event.getVisitors()) {
ps2.setInt(2, v.getUserID());
ps2.executeUpdate();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//findEvent by title
public ArrayList<String> findEventByTitle(String searchTerm) {
ArrayList<String> eventsFound = new ArrayList<>();
//wildcard % doesn't work?
try (Connection conn = getConn()) {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM evenementen WHERE titel LIKE ?");
stmt.setString(1, searchTerm);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("titel"));
eventsFound.add(rs.getString("titel"));
}
if (!rs.next()) {
System.out.println("Done.");
}
} catch (Exception e) {
e.printStackTrace();
}
return eventsFound;
}
//findEvent by date, om te oefenen
public void findEventByDate(Date date){
Connection conn = null;
try {
conn = getConn();
} catch (Exception e) {
e.printStackTrace();
}
try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM evenementen WHERE datum = ?")) {
ps.setDate(1, date);
ResultSet rs = ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("titel"));
System.out.println(rs.getDate("datum"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//deleteEvent by name
public void deleteEvent(String title){
try(Connection conn = getConn()){
PreparedStatement stmt = conn.prepareStatement("DELETE FROM evenementen WHERE titel = ?");
stmt.setString(1, title);
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| EHB-TI/programming-project-groep-a | src/main/java/dao/EventDAO.java | 859 | //save event met meer velden | line_comment | nl | package dao;
import entity.Event;
import entity.User;
import java.sql.*;
import java.util.ArrayList;
public class EventDAO extends BaseDAO {
//save event enkel met titel
public void saveEvent(Event event)
{
try(Connection conn = getConn()){
PreparedStatement stmt = conn.prepareStatement("INSERT INTO evenementen (titel) VALUES (?)");
stmt.setString(1, event.getTitle());
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
//save event<SUF>
public void saveEventMoreFields(Event event){
Connection conn = null;
try {
conn = getConn();
} catch (Exception e) {
e.printStackTrace();
}
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO evenementen (evenementid, titel, datum, organisator, bier) VALUES (NULL, ?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) {
ps.setString(2, event.getTitle());
ps.setDate(3, Date.valueOf(event.getEventDate()));
ps.setString(4, String.valueOf(event.getOrganisingBrewery()));
ps.setString(5, String.valueOf(event.getFeaturedBeer()));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
//?
try (PreparedStatement ps2 = conn.prepareStatement("INSERT INTO aanwezigen (evenementid, gebruikersid) VALUES (NULL, ?)", Statement.RETURN_GENERATED_KEYS)) {
for (User v : event.getVisitors()) {
ps2.setInt(2, v.getUserID());
ps2.executeUpdate();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//findEvent by title
public ArrayList<String> findEventByTitle(String searchTerm) {
ArrayList<String> eventsFound = new ArrayList<>();
//wildcard % doesn't work?
try (Connection conn = getConn()) {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM evenementen WHERE titel LIKE ?");
stmt.setString(1, searchTerm);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("titel"));
eventsFound.add(rs.getString("titel"));
}
if (!rs.next()) {
System.out.println("Done.");
}
} catch (Exception e) {
e.printStackTrace();
}
return eventsFound;
}
//findEvent by date, om te oefenen
public void findEventByDate(Date date){
Connection conn = null;
try {
conn = getConn();
} catch (Exception e) {
e.printStackTrace();
}
try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM evenementen WHERE datum = ?")) {
ps.setDate(1, date);
ResultSet rs = ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("titel"));
System.out.println(rs.getDate("datum"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//deleteEvent by name
public void deleteEvent(String title){
try(Connection conn = getConn()){
PreparedStatement stmt = conn.prepareStatement("DELETE FROM evenementen WHERE titel = ?");
stmt.setString(1, title);
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
210344_0 | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de score van de opdrachten.
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen dingen als het een rekenopdracht is.
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de toets
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
| KemalUzr/project-zeroXess | src/program/Afname.java | 1,034 | // berekent de score van de opdrachten. | line_comment | nl | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de<SUF>
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen dingen als het een rekenopdracht is.
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de toets
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
|
210344_1 | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de score van de opdrachten.
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen dingen als het een rekenopdracht is.
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de toets
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
| KemalUzr/project-zeroXess | src/program/Afname.java | 1,034 | // doet alleen dingen als het een rekenopdracht is. | line_comment | nl | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de score van de opdrachten.
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen<SUF>
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de toets
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
|
210344_2 | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de score van de opdrachten.
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen dingen als het een rekenopdracht is.
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de toets
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
| KemalUzr/project-zeroXess | src/program/Afname.java | 1,034 | // start de toets | line_comment | nl | package program;
import java.util.ArrayList;
public class Afname {
static public ArrayList<Input> opdrachten = new ArrayList<>();
static String type;
// berekent de score van de opdrachten.
public static int BerekenScore() {
int aantalgoed= 0;
if (type.equals("Rekenen")) {
for (Input Shon : opdrachten) {
// doet alleen dingen als het een rekenopdracht is.
if (Shon instanceof RekenInput){
if (((RekenInput) Shon).CheckRekenen()){
aantalgoed++;
}
}
}
}
return aantalgoed;
}
// start de<SUF>
public static void StartToets( String Soorttoets ) {
type = Soorttoets;
if (type.equals("Rekenen")) {
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, 2);
RekenInput opdracht2 = new RekenInput(2, 3);
RekenInput opdracht3 = new RekenInput(3, 7);
RekenInput opdracht4 = new RekenInput(9, 5);
RekenInput opdracht5 = new RekenInput(9, 2);
RekenInput opdracht6 = new RekenInput(6, 2);
RekenInput opdracht7 = new RekenInput(15, 2);
RekenInput opdracht8 = new RekenInput(19, 4);
RekenInput opdracht9 = new RekenInput(1, 2);
RekenInput opdracht10 = new RekenInput(4, 2);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
if (type.equals("Schrijven")) {
opdrachten.clear();
SchrijvenInput opdracht1 = new SchrijvenInput("reading a book daily is very important", "test1");
opdrachten.add(opdracht1);
SchrijvenInput opdracht2 = new SchrijvenInput("exercising is important to stay fit", "test2");
opdrachten.add(opdracht2);
SchrijvenInput opdracht3 = new SchrijvenInput("she had a habit of taking showers in lemonade", "test3");
opdrachten.add(opdracht3);
}
}
// start oefenen
public static void StartOefen( String Soorttoets , String oefenNummer ) {
Integer nummer = Integer.parseInt(oefenNummer);
type = Soorttoets;
if (type.equals("Rekenen")){
opdrachten.clear();
RekenInput opdracht1 = new RekenInput(1, nummer);
RekenInput opdracht2 = new RekenInput(2, nummer);
RekenInput opdracht3 = new RekenInput(3, nummer);
RekenInput opdracht4 = new RekenInput(4, nummer);
RekenInput opdracht5 = new RekenInput(5, nummer);
RekenInput opdracht6 = new RekenInput(6, nummer);
RekenInput opdracht7 = new RekenInput(7, nummer);
RekenInput opdracht8 = new RekenInput(8, nummer);
RekenInput opdracht9 = new RekenInput(9, nummer);
RekenInput opdracht10 = new RekenInput(10 , nummer);
opdrachten.add(opdracht1);
opdrachten.add(opdracht2);
opdrachten.add(opdracht3);
opdrachten.add(opdracht4);
opdrachten.add(opdracht5);
opdrachten.add(opdracht6);
opdrachten.add(opdracht7);
opdrachten.add(opdracht8);
opdrachten.add(opdracht9);
opdrachten.add(opdracht10);
}
}
}
|
210365_6 | package cbookeditor.impl;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.TransferHandler;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookService;
import org.cbook.cbookif.CBookWidgetEditIF;
import org.cbook.cbookif.CBookWidgetIF;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import cbookeditor.Wrapper;
public class WidgetContainer extends JPanel implements CBookContext {
private String id = UUID.randomUUID().toString();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
map.put(Constants.UUID, id);
}
static class SizesPanel extends JPanel implements ActionListener {
JTextField w,h;
CBookWidgetEditIF editor;
JCheckBox popup;
public SizesPanel(CBookWidgetEditIF editor) {
super();
this.editor = editor;
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
Dimension dim = editor.getInstanceSize();
w = new JTextField(String.valueOf(dim.width));
h = new JTextField(String.valueOf(dim.height));
w.addActionListener(this);
h.addActionListener(this);
add(new JLabel("dim:"));
add(w);
add(new JLabel("×"));
add(h);
popup = new JCheckBox("popup");
add(popup);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == w) {
editor.setInstanceWidth(Integer.parseInt(w.getText()));
} else if(source == h ) {
editor.setInstanceHeight(Integer.parseInt(h.getText()));
}
}
public Dimension getInstanceSize() {
editor.setInstanceWidth(Integer.parseInt(w.getText()));
editor.setInstanceHeight(Integer.parseInt(h.getText()));
return editor.getInstanceSize();
}
public boolean isPopup() {
return popup.isSelected();
}
public void setPopup(boolean popup) {
this.popup.setSelected(popup);
}
}
private static final String EMPTY_MAP = "{}";
static DataFlavor widgetFlavor;
static {
try {
widgetFlavor =
new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + Holder.class.getName() + '\"', null, Holder.class.getClassLoader());
} catch (ClassNotFoundException e) {
// Should not happen!
e.printStackTrace();
}
//System.out.println(widgetFlavor);
//new DataFlavor(Holder.class, "WidgetContainer Holder");
}
static DataFlavor[] flavors = { widgetFlavor };
static class GlassComponent extends JPanel implements MouseListener, DropTargetListener {
class MyTransferHandler extends TransferHandler{
MyTransferHandler() {
super("container");
}
@Override
public Icon getVisualRepresentation(Transferable arg0) {
//return super.getVisualRepresentation(arg0);
return container.icon;
}
public boolean canImport(JComponent c, DataFlavor[] f){
for(DataFlavor d:f){
if(d.equals(widgetFlavor))
return true;
}
return false;
}
public boolean importData(JComponent comp, Transferable t, Point p){
return true;
}
@Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_REFERENCE;
}
public Transferable createTransferable(JComponent c){
return new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return widgetFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
{ //dragSource = getContainer();
return new Holder(getContainer());
}
throw new UnsupportedFlavorException(flavor);
}
};
}
}
private WidgetContainer container;
private TransferHandler transfer = new MyTransferHandler();
private DropTarget target;
private boolean exited;
public WidgetContainer getContainer() {
return this.container;
}
public GlassComponent(WidgetContainer container) {
super(null);
this.container = container;
setOpaque(false);
setTransferHandler(transfer);
target = new DropTarget(this, this);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
if(e.isShiftDown()) // is linking...
{
exited = true;
TransferHandler handle = getTransferHandler();
handle.exportAsDrag(this, e, handle.getSourceActions(null));
} else
exited = false;
}
public void mouseReleased(MouseEvent e) {
if(!exited) container.openEditorDialog();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
exited = true;
}
public void dragEnter(DropTargetDragEvent dtde) {
//System.out.println("drag enter " + dtde);
}
public void dragOver(DropTargetDragEvent dtde) {}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dtde) {
}
@SuppressWarnings("unchecked")
public void drop(DropTargetDropEvent dtde) {
//System.out.println("drag drop " + dtde);
Transferable t = dtde.getTransferable();
DataFlavor tt = t.getTransferDataFlavors()[0];
try {
Holder o = (Holder) t.getTransferData(tt);
WidgetContainer source = o.getObject();
String[] acceptedCmds = container.getAcceptedCmds();
if(acceptedCmds != null)
{
String[] sendCmds = source.getSendCmds();
if(sendCmds != null)
{ Set<String> destSet = new TreeSet<String>(Arrays.asList(sendCmds));
Set<String> sourceSet = new TreeSet<String>(Arrays.asList(acceptedCmds));
destSet.retainAll(sourceSet);
if(!destSet.isEmpty())
{
source.connect(container, destSet);
}
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dtde.dropComplete(true);
}
}
JComponent content;
GlassComponent glass = new GlassComponent(this);
private CBookWidgetIF widget;
private CBookWidgetInstanceIF instance;
private CBookWidgetEditIF editor;
private CBookEventHandler handler = new CBookEventHandler(this);
private Icon icon;
public String[] getAcceptedCmds() {
return editor.getAcceptedCmds();
}
List connections = new JSONArray();
public void connect(WidgetContainer dest, Set set) {
if(dest == this) return;
CBookEventListener listener = dest.instance.asEventListener();
if(listener == null) return;
Object[] possibleValues = set.toArray();
Object selectedValue = JOptionPane.showInputDialog(this,
"Choose one", "Command",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
String command = (String) selectedValue;
if(command != null)
{
instance.addCBookEventListener(listener, command);
connections.add(Collections.singletonMap(command, dest.getId()));
}
}
public String[] getSendCmds() {
return editor.getSendCmds();
}
private HashMap<String, Object> map = new HashMap();
private CBookContext context;
String state = EMPTY_MAP;
private String launchData = EMPTY_MAP;
private Dimension instanceSize;
private boolean popup;
private JButton popupBtn;
private JDialog popupDlg;
private ActionListener popupAction = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(popupDlg == null)
{
popupDlg = new JDialog(JOptionPane.getFrameForComponent(WidgetContainer.this), widget.toString(), false);
popupDlg.setContentPane(content);
popupDlg.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
popupDlg.setSize(content.getSize()); // TODO insets.
}
popupDlg.setVisible(true);
}
};
public Dimension getMaximumSize() {
return getSize();
}
public Dimension getPreferredSize() {
if(popup)
return popupBtn.getPreferredSize();
return new Dimension(instanceSize);
}
WidgetContainer(CBookWidgetIF widget, CBookEventListener listener, CBookContext context) {
super(null);
this.context = context;
this.widget = widget;
handler.addCBookEventListener(listener, null);
instance = widget.getInstance(this);
editor = widget.getEditor(this);
try {
icon = widget.getIcon();
} catch (Exception e) {
e.printStackTrace();
}
if(icon == null) icon = new DefaultIcon();
popupBtn = new JButton(icon);
launchData = JSONValue.toJSONString(editor.getLaunchData());
instance.setAssessmentMode(AssessmentMode.OEFENEN);
instance.addCBookEventListener(listener, null);
content = instance.asComponent();
instanceSize = editor.getInstanceSize();
map.put(Constants.INSTANCE_SIZE, instanceSize);
map.put(Constants.UUID, id);
content.setSize(instanceSize);
content.setLocation(0, 0);
glass.setSize(instanceSize);
setSize(instanceSize);
add(glass); // top?
add(content);
add(popupBtn);
instance.init();
Map launchmap = (Map)JSONValue.parse(launchData);
if(launchmap == null)
launchmap = Collections.emptyMap();
else
launchmap = Collections.unmodifiableMap(launchmap);
try {
instance.setLaunchData(launchmap, getRandomVars());
} catch (Exception e) {
e.printStackTrace();
}
}
protected boolean openEditorDialog() {
JComponent component = editor.asComponent();
JPanel panel = new JPanel(new BorderLayout());
panel.add(component, BorderLayout.CENTER);
SizesPanel sizes = new SizesPanel(editor);
sizes.setPopup(popup);
panel.add(sizes, BorderLayout.SOUTH);
// HeaderPanel?
HeaderPanel header = new HeaderPanel(editor, map);
//JPanel header = new JPanel();
panel.add(header, BorderLayout.NORTH);
Map<String,?> data = (Map<String,?>) JSONValue.parse(launchData);
data = Collections.unmodifiableMap(data);
editor.setLaunchData(data);
int r = JOptionPane.showConfirmDialog(this, panel, widget.toString(),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);
if(r == JOptionPane.OK_OPTION)
{
launchData = JSONValue.toJSONString(editor.getLaunchData());
handler.fire("getLaunchData", "launchData", launchData);
instanceSize = sizes.getInstanceSize();
state = EMPTY_MAP;
popup = sizes.isPopup();
setSize(getPreferredSize());
glass.setSize(getSize());
if(popup) {
remove(content);
popupBtn.setVisible(true);
popupBtn.setSize(popupBtn.getPreferredSize());
} else {
add(content);
popupBtn.setVisible(false);
}
header.updateMap();
map.put(Constants.INSTANCE_SIZE, instanceSize);
content.setSize(instanceSize);
content.invalidate();
content.validate();
instance.init();
data = (Map<String,?>)JSONValue.parse(launchData);
if(data == null)
data = Collections.emptyMap();
else
data = Collections.unmodifiableMap(data);
instance.setLaunchData(data, getRandomVars());
return true;
}
return false;
}
private Map getRandomVars() {
Object o = context.getProperty("randomVars");
if(o instanceof Map) {
return (Map)o;
}
return Collections.EMPTY_MAP;
}
public void setViewMode(boolean viewing) {
if(viewing)
{ glass.setVisible(false);
popupBtn.addActionListener(popupAction);
// TODO een nieuwe instance gebruiken?
// instance = widget.getInstance(context);
// component = instance.asComponent();
// listener = instace.asEventListener();
// wiring...
instance.setState(getState());
instance.start();
} else {
popupBtn.removeActionListener(popupAction);
glass.setVisible(true);
instance.stop();
Map stateMap = instance.getState();
setState(stateMap);
handler.fire("getState", "state", state);
instance.setState(Collections.EMPTY_MAP);
if(popupDlg != null) popupDlg.hide();
}
;
}
public void setState(Map map) {
state = JSONValue.toJSONString(map);
}
public Object getProperty(String key) {
if(map.containsKey(key))
return map.get(key);
return context.getProperty(key);
}
public int getScore() {
return instance.getScore();
}
public SuccessStatus getSuccessStatus() {
return instance.getSuccessStatus();
}
public int getMaxScore() {
return editor.getMaxScore();
}
public static WidgetContainer newInstance(CBookService service,
CBookEventListener listener, JTextPane text, CBookContext context) {
Object[] possibleValues = service.getRegisteredWidgets().toArray();
Object selectedValue = JOptionPane.showInputDialog(text,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if(selectedValue instanceof CBookWidgetIF)
{
WidgetContainer wc = new WidgetContainer((CBookWidgetIF) selectedValue, listener, context);
if( wc.openEditorDialog() );
return wc;
}
return null;
}
public void reset() {
instance.reset();
}
public void destroy() {
if(!glass.isVisible())
instance.stop();
instance.destroy();
}
public void setAssessmentMode(AssessmentMode mode) {
instance.setAssessmentMode(mode);
}
public void acceptCBookEvent(CBookEvent event) {
String[] cmds = editor.getAcceptedCmds();
if(cmds == null) return;
List<String> accepts = Arrays.asList(cmds);
if(accepts.contains(event.getCommand()))
instance.asEventListener().acceptCBookEvent(event);
}
public Map getLaunchData() {
Map<String,Object> data = new HashMap<String, Object>();
data.put("launchData", JSONValue.parse(launchData));
data.put("width", instanceSize.width);
data.put("height", instanceSize.height);
data.put("popup", popup);
data.put(Constants.MAX_SCORE, getMaxScore());
data.put(Constants.LOGGING, getProperty(Constants.LOGGING));
data.put(Constants.LOG_ID, getProperty(Constants.LOG_ID));
data.put("class", widget instanceof Wrapper ? ((Wrapper) widget).getClassName() : widget.getClass().getName());
data.put("connections", connections);
data.put("id", getId());
return data;
}
public WidgetContainer(Map launchData, CBookService service, CBookContext context, CBookEventListener listener) {
super(null);
this.context = context;
map.putAll(launchData);
handler.addCBookEventListener(listener, null);
setLocale((Locale) getProperty("locale"));
Object value;
value = map.remove("id");
if(value!=null) setId(value.toString());
value = map.remove("connections");
if(value!=null) connections = (List) value;
value = map.remove("class");
widget = service.widgetForName(value.toString());
editor = widget.getEditor(this);
value = map.get("launchData");
this.launchData = JSONValue.toJSONString(value);
editor.setLaunchData((Map<String, ?>) value);
instanceSize = editor.getInstanceSize();
value = map.remove("width");
if(value!=null)
{
instanceSize.width = ((Number) value).intValue();
editor.setInstanceWidth(instanceSize.width);
}
value = map.remove("height");
if(value!=null)
{
instanceSize.height = ((Number)value).intValue();
editor.setInstanceHeight(instanceSize.height);
}
map.put(Constants.INSTANCE_SIZE, instanceSize);
value = map.remove("popup");
popup = Boolean.TRUE.equals(value);
instance = widget.getInstance(this);
content = instance.asComponent();
content.setSize(instanceSize);
content.setLocation(0, 0);
try {
icon = widget.getIcon();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(icon == null) icon = new DefaultIcon();
popupBtn = new JButton(icon);
popupBtn.addActionListener(popupAction);
popupBtn.setVisible(popup);
popupBtn.setSize(popupBtn.getPreferredSize());
setSize(getPreferredSize());
glass.setSize(getSize());
add(glass);
if(!popup) add(content);
add(popupBtn);
instance.init();
try {
Map launchmap = (Map)map.remove("launchData");
if (launchmap == null)
launchmap = Collections.emptyMap();
else
launchmap = Collections.unmodifiableMap(launchmap);
instance.setLaunchData(launchmap, getRandomVars());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initConnections(CBookContext ids) {
Iterator iter = connections.iterator();
while (iter.hasNext()) {
Map<String,String> type = (Map) iter.next();
Map.Entry<String,String> entry = type.entrySet().iterator().next();
WidgetContainer w = (WidgetContainer) ids.getProperty(entry.getValue());
if(w != null)
instance.addCBookEventListener(w.instance.asEventListener(), entry.getKey());
else
iter.remove();
}
}
public Map getState() {
return (Map) JSONValue.parse(state);
}
}
| vpapakir/mymcsqared | CBookEditor/src/cbookeditor/impl/WidgetContainer.java | 5,236 | // TODO een nieuwe instance gebruiken? | line_comment | nl | package cbookeditor.impl;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.TransferHandler;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookService;
import org.cbook.cbookif.CBookWidgetEditIF;
import org.cbook.cbookif.CBookWidgetIF;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import cbookeditor.Wrapper;
public class WidgetContainer extends JPanel implements CBookContext {
private String id = UUID.randomUUID().toString();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
map.put(Constants.UUID, id);
}
static class SizesPanel extends JPanel implements ActionListener {
JTextField w,h;
CBookWidgetEditIF editor;
JCheckBox popup;
public SizesPanel(CBookWidgetEditIF editor) {
super();
this.editor = editor;
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
Dimension dim = editor.getInstanceSize();
w = new JTextField(String.valueOf(dim.width));
h = new JTextField(String.valueOf(dim.height));
w.addActionListener(this);
h.addActionListener(this);
add(new JLabel("dim:"));
add(w);
add(new JLabel("×"));
add(h);
popup = new JCheckBox("popup");
add(popup);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == w) {
editor.setInstanceWidth(Integer.parseInt(w.getText()));
} else if(source == h ) {
editor.setInstanceHeight(Integer.parseInt(h.getText()));
}
}
public Dimension getInstanceSize() {
editor.setInstanceWidth(Integer.parseInt(w.getText()));
editor.setInstanceHeight(Integer.parseInt(h.getText()));
return editor.getInstanceSize();
}
public boolean isPopup() {
return popup.isSelected();
}
public void setPopup(boolean popup) {
this.popup.setSelected(popup);
}
}
private static final String EMPTY_MAP = "{}";
static DataFlavor widgetFlavor;
static {
try {
widgetFlavor =
new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + Holder.class.getName() + '\"', null, Holder.class.getClassLoader());
} catch (ClassNotFoundException e) {
// Should not happen!
e.printStackTrace();
}
//System.out.println(widgetFlavor);
//new DataFlavor(Holder.class, "WidgetContainer Holder");
}
static DataFlavor[] flavors = { widgetFlavor };
static class GlassComponent extends JPanel implements MouseListener, DropTargetListener {
class MyTransferHandler extends TransferHandler{
MyTransferHandler() {
super("container");
}
@Override
public Icon getVisualRepresentation(Transferable arg0) {
//return super.getVisualRepresentation(arg0);
return container.icon;
}
public boolean canImport(JComponent c, DataFlavor[] f){
for(DataFlavor d:f){
if(d.equals(widgetFlavor))
return true;
}
return false;
}
public boolean importData(JComponent comp, Transferable t, Point p){
return true;
}
@Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_REFERENCE;
}
public Transferable createTransferable(JComponent c){
return new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return widgetFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
{ //dragSource = getContainer();
return new Holder(getContainer());
}
throw new UnsupportedFlavorException(flavor);
}
};
}
}
private WidgetContainer container;
private TransferHandler transfer = new MyTransferHandler();
private DropTarget target;
private boolean exited;
public WidgetContainer getContainer() {
return this.container;
}
public GlassComponent(WidgetContainer container) {
super(null);
this.container = container;
setOpaque(false);
setTransferHandler(transfer);
target = new DropTarget(this, this);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
if(e.isShiftDown()) // is linking...
{
exited = true;
TransferHandler handle = getTransferHandler();
handle.exportAsDrag(this, e, handle.getSourceActions(null));
} else
exited = false;
}
public void mouseReleased(MouseEvent e) {
if(!exited) container.openEditorDialog();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
exited = true;
}
public void dragEnter(DropTargetDragEvent dtde) {
//System.out.println("drag enter " + dtde);
}
public void dragOver(DropTargetDragEvent dtde) {}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dtde) {
}
@SuppressWarnings("unchecked")
public void drop(DropTargetDropEvent dtde) {
//System.out.println("drag drop " + dtde);
Transferable t = dtde.getTransferable();
DataFlavor tt = t.getTransferDataFlavors()[0];
try {
Holder o = (Holder) t.getTransferData(tt);
WidgetContainer source = o.getObject();
String[] acceptedCmds = container.getAcceptedCmds();
if(acceptedCmds != null)
{
String[] sendCmds = source.getSendCmds();
if(sendCmds != null)
{ Set<String> destSet = new TreeSet<String>(Arrays.asList(sendCmds));
Set<String> sourceSet = new TreeSet<String>(Arrays.asList(acceptedCmds));
destSet.retainAll(sourceSet);
if(!destSet.isEmpty())
{
source.connect(container, destSet);
}
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dtde.dropComplete(true);
}
}
JComponent content;
GlassComponent glass = new GlassComponent(this);
private CBookWidgetIF widget;
private CBookWidgetInstanceIF instance;
private CBookWidgetEditIF editor;
private CBookEventHandler handler = new CBookEventHandler(this);
private Icon icon;
public String[] getAcceptedCmds() {
return editor.getAcceptedCmds();
}
List connections = new JSONArray();
public void connect(WidgetContainer dest, Set set) {
if(dest == this) return;
CBookEventListener listener = dest.instance.asEventListener();
if(listener == null) return;
Object[] possibleValues = set.toArray();
Object selectedValue = JOptionPane.showInputDialog(this,
"Choose one", "Command",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
String command = (String) selectedValue;
if(command != null)
{
instance.addCBookEventListener(listener, command);
connections.add(Collections.singletonMap(command, dest.getId()));
}
}
public String[] getSendCmds() {
return editor.getSendCmds();
}
private HashMap<String, Object> map = new HashMap();
private CBookContext context;
String state = EMPTY_MAP;
private String launchData = EMPTY_MAP;
private Dimension instanceSize;
private boolean popup;
private JButton popupBtn;
private JDialog popupDlg;
private ActionListener popupAction = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(popupDlg == null)
{
popupDlg = new JDialog(JOptionPane.getFrameForComponent(WidgetContainer.this), widget.toString(), false);
popupDlg.setContentPane(content);
popupDlg.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
popupDlg.setSize(content.getSize()); // TODO insets.
}
popupDlg.setVisible(true);
}
};
public Dimension getMaximumSize() {
return getSize();
}
public Dimension getPreferredSize() {
if(popup)
return popupBtn.getPreferredSize();
return new Dimension(instanceSize);
}
WidgetContainer(CBookWidgetIF widget, CBookEventListener listener, CBookContext context) {
super(null);
this.context = context;
this.widget = widget;
handler.addCBookEventListener(listener, null);
instance = widget.getInstance(this);
editor = widget.getEditor(this);
try {
icon = widget.getIcon();
} catch (Exception e) {
e.printStackTrace();
}
if(icon == null) icon = new DefaultIcon();
popupBtn = new JButton(icon);
launchData = JSONValue.toJSONString(editor.getLaunchData());
instance.setAssessmentMode(AssessmentMode.OEFENEN);
instance.addCBookEventListener(listener, null);
content = instance.asComponent();
instanceSize = editor.getInstanceSize();
map.put(Constants.INSTANCE_SIZE, instanceSize);
map.put(Constants.UUID, id);
content.setSize(instanceSize);
content.setLocation(0, 0);
glass.setSize(instanceSize);
setSize(instanceSize);
add(glass); // top?
add(content);
add(popupBtn);
instance.init();
Map launchmap = (Map)JSONValue.parse(launchData);
if(launchmap == null)
launchmap = Collections.emptyMap();
else
launchmap = Collections.unmodifiableMap(launchmap);
try {
instance.setLaunchData(launchmap, getRandomVars());
} catch (Exception e) {
e.printStackTrace();
}
}
protected boolean openEditorDialog() {
JComponent component = editor.asComponent();
JPanel panel = new JPanel(new BorderLayout());
panel.add(component, BorderLayout.CENTER);
SizesPanel sizes = new SizesPanel(editor);
sizes.setPopup(popup);
panel.add(sizes, BorderLayout.SOUTH);
// HeaderPanel?
HeaderPanel header = new HeaderPanel(editor, map);
//JPanel header = new JPanel();
panel.add(header, BorderLayout.NORTH);
Map<String,?> data = (Map<String,?>) JSONValue.parse(launchData);
data = Collections.unmodifiableMap(data);
editor.setLaunchData(data);
int r = JOptionPane.showConfirmDialog(this, panel, widget.toString(),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);
if(r == JOptionPane.OK_OPTION)
{
launchData = JSONValue.toJSONString(editor.getLaunchData());
handler.fire("getLaunchData", "launchData", launchData);
instanceSize = sizes.getInstanceSize();
state = EMPTY_MAP;
popup = sizes.isPopup();
setSize(getPreferredSize());
glass.setSize(getSize());
if(popup) {
remove(content);
popupBtn.setVisible(true);
popupBtn.setSize(popupBtn.getPreferredSize());
} else {
add(content);
popupBtn.setVisible(false);
}
header.updateMap();
map.put(Constants.INSTANCE_SIZE, instanceSize);
content.setSize(instanceSize);
content.invalidate();
content.validate();
instance.init();
data = (Map<String,?>)JSONValue.parse(launchData);
if(data == null)
data = Collections.emptyMap();
else
data = Collections.unmodifiableMap(data);
instance.setLaunchData(data, getRandomVars());
return true;
}
return false;
}
private Map getRandomVars() {
Object o = context.getProperty("randomVars");
if(o instanceof Map) {
return (Map)o;
}
return Collections.EMPTY_MAP;
}
public void setViewMode(boolean viewing) {
if(viewing)
{ glass.setVisible(false);
popupBtn.addActionListener(popupAction);
// TODO een<SUF>
// instance = widget.getInstance(context);
// component = instance.asComponent();
// listener = instace.asEventListener();
// wiring...
instance.setState(getState());
instance.start();
} else {
popupBtn.removeActionListener(popupAction);
glass.setVisible(true);
instance.stop();
Map stateMap = instance.getState();
setState(stateMap);
handler.fire("getState", "state", state);
instance.setState(Collections.EMPTY_MAP);
if(popupDlg != null) popupDlg.hide();
}
;
}
public void setState(Map map) {
state = JSONValue.toJSONString(map);
}
public Object getProperty(String key) {
if(map.containsKey(key))
return map.get(key);
return context.getProperty(key);
}
public int getScore() {
return instance.getScore();
}
public SuccessStatus getSuccessStatus() {
return instance.getSuccessStatus();
}
public int getMaxScore() {
return editor.getMaxScore();
}
public static WidgetContainer newInstance(CBookService service,
CBookEventListener listener, JTextPane text, CBookContext context) {
Object[] possibleValues = service.getRegisteredWidgets().toArray();
Object selectedValue = JOptionPane.showInputDialog(text,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if(selectedValue instanceof CBookWidgetIF)
{
WidgetContainer wc = new WidgetContainer((CBookWidgetIF) selectedValue, listener, context);
if( wc.openEditorDialog() );
return wc;
}
return null;
}
public void reset() {
instance.reset();
}
public void destroy() {
if(!glass.isVisible())
instance.stop();
instance.destroy();
}
public void setAssessmentMode(AssessmentMode mode) {
instance.setAssessmentMode(mode);
}
public void acceptCBookEvent(CBookEvent event) {
String[] cmds = editor.getAcceptedCmds();
if(cmds == null) return;
List<String> accepts = Arrays.asList(cmds);
if(accepts.contains(event.getCommand()))
instance.asEventListener().acceptCBookEvent(event);
}
public Map getLaunchData() {
Map<String,Object> data = new HashMap<String, Object>();
data.put("launchData", JSONValue.parse(launchData));
data.put("width", instanceSize.width);
data.put("height", instanceSize.height);
data.put("popup", popup);
data.put(Constants.MAX_SCORE, getMaxScore());
data.put(Constants.LOGGING, getProperty(Constants.LOGGING));
data.put(Constants.LOG_ID, getProperty(Constants.LOG_ID));
data.put("class", widget instanceof Wrapper ? ((Wrapper) widget).getClassName() : widget.getClass().getName());
data.put("connections", connections);
data.put("id", getId());
return data;
}
public WidgetContainer(Map launchData, CBookService service, CBookContext context, CBookEventListener listener) {
super(null);
this.context = context;
map.putAll(launchData);
handler.addCBookEventListener(listener, null);
setLocale((Locale) getProperty("locale"));
Object value;
value = map.remove("id");
if(value!=null) setId(value.toString());
value = map.remove("connections");
if(value!=null) connections = (List) value;
value = map.remove("class");
widget = service.widgetForName(value.toString());
editor = widget.getEditor(this);
value = map.get("launchData");
this.launchData = JSONValue.toJSONString(value);
editor.setLaunchData((Map<String, ?>) value);
instanceSize = editor.getInstanceSize();
value = map.remove("width");
if(value!=null)
{
instanceSize.width = ((Number) value).intValue();
editor.setInstanceWidth(instanceSize.width);
}
value = map.remove("height");
if(value!=null)
{
instanceSize.height = ((Number)value).intValue();
editor.setInstanceHeight(instanceSize.height);
}
map.put(Constants.INSTANCE_SIZE, instanceSize);
value = map.remove("popup");
popup = Boolean.TRUE.equals(value);
instance = widget.getInstance(this);
content = instance.asComponent();
content.setSize(instanceSize);
content.setLocation(0, 0);
try {
icon = widget.getIcon();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(icon == null) icon = new DefaultIcon();
popupBtn = new JButton(icon);
popupBtn.addActionListener(popupAction);
popupBtn.setVisible(popup);
popupBtn.setSize(popupBtn.getPreferredSize());
setSize(getPreferredSize());
glass.setSize(getSize());
add(glass);
if(!popup) add(content);
add(popupBtn);
instance.init();
try {
Map launchmap = (Map)map.remove("launchData");
if (launchmap == null)
launchmap = Collections.emptyMap();
else
launchmap = Collections.unmodifiableMap(launchmap);
instance.setLaunchData(launchmap, getRandomVars());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initConnections(CBookContext ids) {
Iterator iter = connections.iterator();
while (iter.hasNext()) {
Map<String,String> type = (Map) iter.next();
Map.Entry<String,String> entry = type.entrySet().iterator().next();
WidgetContainer w = (WidgetContainer) ids.getProperty(entry.getValue());
if(w != null)
instance.addCBookEventListener(w.instance.asEventListener(), entry.getKey());
else
iter.remove();
}
}
public Map getState() {
return (Map) JSONValue.parse(state);
}
}
|
210402_1 | /*
* GeoTools Sample code and Tutorials by Open Source Geospatial Foundation, and others
* https://docs.geotools.org
*
* To the extent possible under law, the author(s) have dedicated all copyright
* and related and neighboring rights to this software to the public domain worldwide.
* This software is distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this
* software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
package org.geotools.grid;
import java.awt.Color;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.geotools.api.data.FileDataStore;
import org.geotools.api.data.FileDataStoreFinder;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.grid.hexagon.HexagonOrientation;
import org.geotools.grid.hexagon.Hexagons;
import org.geotools.grid.oblong.Oblongs;
import org.geotools.grid.ortholine.LineOrientation;
import org.geotools.grid.ortholine.OrthoLineDef;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Polygon;
public class GridExamples {
private void exampleSquareGrid() {
// exampleSquareGrid start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110.0, 150.0, -45.0, -5.0, DefaultGeographicCRS.WGS84);
SimpleFeatureSource grid = Grids.createSquareGrid(gridBounds, 10.0);
// exampleSquareGrid end
}
private void exampleDensifiedSquareGrid() {
// exampleDensifiedSquareGrid start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110, 160, -45, -8, DefaultGeographicCRS.WGS84);
double squareWidth = 20.0;
// max distance between vertices
double vertexSpacing = squareWidth / 20;
SimpleFeatureSource grid = Grids.createSquareGrid(gridBounds, squareWidth, vertexSpacing);
// exampleDensifiedSquareGrid end
}
private void exampleHexagonalGrid() {
// exampleHexagonalGrid start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
// length of each hexagon edge
double sideLen = 5.0;
SimpleFeatureSource grid = Grids.createHexagonalGrid(gridBounds, sideLen);
// exampleHexagonalGrid end
}
private void exampleCustomFeatureType() {
// exampleCustomFeatureType start
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName("hextype");
typeBuilder.add("hexagon", Polygon.class, (CoordinateReferenceSystem) null);
typeBuilder.add("color", Color.class);
SimpleFeatureType TYPE = typeBuilder.buildFeatureType();
final ReferencedEnvelope bounds = new ReferencedEnvelope(0, 100, 0, 100, null);
GridFeatureBuilder builder =
new GridFeatureBuilder(TYPE) {
@Override
public void setAttributes(GridElement element, Map<String, Object> attributes) {
PolygonElement polyEl = (PolygonElement) element;
int g = (int) (255 * polyEl.getCenter().x / bounds.getWidth());
int b = (int) (255 * polyEl.getCenter().y / bounds.getHeight());
attributes.put("color", new Color(0, g, b));
}
};
// Pass the GridFeatureBuilder object to the createHexagonalGrid method
// (the -1 value here indicates that we don't need densified polygons)
final double sideLen = 5.0;
SimpleFeatureSource grid = Grids.createHexagonalGrid(bounds, sideLen, -1, builder);
// exampleCustomFeatureType end
}
private void exampleIntersection() throws Exception {
// exampleIntersection start
// Load the outline of Australia from a shapefile
URL url = getClass().getResource("oz.shp");
FileDataStore dataStore = FileDataStoreFinder.getDataStore(url);
SimpleFeatureSource ozMapSource = dataStore.getFeatureSource();
// Set the grid size (1 degree) and create a bounding envelope
// that is neatly aligned with the grid size
double sideLen = 1.0;
ReferencedEnvelope gridBounds = Envelopes.expandToInclude(ozMapSource.getBounds(), sideLen);
// Create a feature type
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
tb.setName("grid");
tb.add(
GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME,
Polygon.class,
gridBounds.getCoordinateReferenceSystem());
tb.add("id", Integer.class);
SimpleFeatureType TYPE = tb.buildFeatureType();
// Build the grid the custom feature builder class
GridFeatureBuilder builder = new IntersectionBuilder(TYPE, ozMapSource);
SimpleFeatureSource grid = Grids.createHexagonalGrid(gridBounds, sideLen, -1, builder);
// exampleIntersection end
}
private void exampleHexagonOrientation() {
// exampleHexagonOrientation start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
double sideLen = 5.0;
GridFeatureBuilder builder = new DefaultGridFeatureBuilder();
SimpleFeatureSource grid =
Hexagons.createGrid(gridBounds, sideLen, HexagonOrientation.ANGLED, builder);
// exampleHexagonOrientation end
}
private void exampleOblong() {
// exampleOblong start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
double width = 10.0;
double height = 5.0;
GridFeatureBuilder builder = new DefaultGridFeatureBuilder();
SimpleFeatureSource grid = Oblongs.createGrid(gridBounds, width, height, builder);
// exampleOblong end
}
private void exampleMajorMinorLines() {
// exampleMajorMinorLines start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110.0, 150.0, -45.0, -5.0, DefaultGeographicCRS.WGS84);
/*
* Line definitions:
* major lines at 10 degree spacing are indicated by level = 2
* minor lines at 2 degree spacing are indicated by level = 1
* (level values are arbitrary; only rank order matters)
*/
List<OrthoLineDef> lineDefs =
Arrays.asList(
// vertical (longitude) lines
new OrthoLineDef(LineOrientation.VERTICAL, 2, 10.0),
new OrthoLineDef(LineOrientation.VERTICAL, 1, 2.0),
// horizontal (latitude) lines
new OrthoLineDef(LineOrientation.HORIZONTAL, 2, 10.0),
new OrthoLineDef(LineOrientation.HORIZONTAL, 1, 2.0));
// Specify vertex spacing to get "densified" polygons
double vertexSpacing = 0.1;
SimpleFeatureSource grid = Lines.createOrthoLines(gridBounds, lineDefs, vertexSpacing);
// exampleMajorMinorLines end
}
}
| geotools/geotools | docs/src/main/java/org/geotools/grid/GridExamples.java | 1,868 | // max distance between vertices | line_comment | nl | /*
* GeoTools Sample code and Tutorials by Open Source Geospatial Foundation, and others
* https://docs.geotools.org
*
* To the extent possible under law, the author(s) have dedicated all copyright
* and related and neighboring rights to this software to the public domain worldwide.
* This software is distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this
* software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
package org.geotools.grid;
import java.awt.Color;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.geotools.api.data.FileDataStore;
import org.geotools.api.data.FileDataStoreFinder;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.grid.hexagon.HexagonOrientation;
import org.geotools.grid.hexagon.Hexagons;
import org.geotools.grid.oblong.Oblongs;
import org.geotools.grid.ortholine.LineOrientation;
import org.geotools.grid.ortholine.OrthoLineDef;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Polygon;
public class GridExamples {
private void exampleSquareGrid() {
// exampleSquareGrid start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110.0, 150.0, -45.0, -5.0, DefaultGeographicCRS.WGS84);
SimpleFeatureSource grid = Grids.createSquareGrid(gridBounds, 10.0);
// exampleSquareGrid end
}
private void exampleDensifiedSquareGrid() {
// exampleDensifiedSquareGrid start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110, 160, -45, -8, DefaultGeographicCRS.WGS84);
double squareWidth = 20.0;
// max distance<SUF>
double vertexSpacing = squareWidth / 20;
SimpleFeatureSource grid = Grids.createSquareGrid(gridBounds, squareWidth, vertexSpacing);
// exampleDensifiedSquareGrid end
}
private void exampleHexagonalGrid() {
// exampleHexagonalGrid start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
// length of each hexagon edge
double sideLen = 5.0;
SimpleFeatureSource grid = Grids.createHexagonalGrid(gridBounds, sideLen);
// exampleHexagonalGrid end
}
private void exampleCustomFeatureType() {
// exampleCustomFeatureType start
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName("hextype");
typeBuilder.add("hexagon", Polygon.class, (CoordinateReferenceSystem) null);
typeBuilder.add("color", Color.class);
SimpleFeatureType TYPE = typeBuilder.buildFeatureType();
final ReferencedEnvelope bounds = new ReferencedEnvelope(0, 100, 0, 100, null);
GridFeatureBuilder builder =
new GridFeatureBuilder(TYPE) {
@Override
public void setAttributes(GridElement element, Map<String, Object> attributes) {
PolygonElement polyEl = (PolygonElement) element;
int g = (int) (255 * polyEl.getCenter().x / bounds.getWidth());
int b = (int) (255 * polyEl.getCenter().y / bounds.getHeight());
attributes.put("color", new Color(0, g, b));
}
};
// Pass the GridFeatureBuilder object to the createHexagonalGrid method
// (the -1 value here indicates that we don't need densified polygons)
final double sideLen = 5.0;
SimpleFeatureSource grid = Grids.createHexagonalGrid(bounds, sideLen, -1, builder);
// exampleCustomFeatureType end
}
private void exampleIntersection() throws Exception {
// exampleIntersection start
// Load the outline of Australia from a shapefile
URL url = getClass().getResource("oz.shp");
FileDataStore dataStore = FileDataStoreFinder.getDataStore(url);
SimpleFeatureSource ozMapSource = dataStore.getFeatureSource();
// Set the grid size (1 degree) and create a bounding envelope
// that is neatly aligned with the grid size
double sideLen = 1.0;
ReferencedEnvelope gridBounds = Envelopes.expandToInclude(ozMapSource.getBounds(), sideLen);
// Create a feature type
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
tb.setName("grid");
tb.add(
GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME,
Polygon.class,
gridBounds.getCoordinateReferenceSystem());
tb.add("id", Integer.class);
SimpleFeatureType TYPE = tb.buildFeatureType();
// Build the grid the custom feature builder class
GridFeatureBuilder builder = new IntersectionBuilder(TYPE, ozMapSource);
SimpleFeatureSource grid = Grids.createHexagonalGrid(gridBounds, sideLen, -1, builder);
// exampleIntersection end
}
private void exampleHexagonOrientation() {
// exampleHexagonOrientation start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
double sideLen = 5.0;
GridFeatureBuilder builder = new DefaultGridFeatureBuilder();
SimpleFeatureSource grid =
Hexagons.createGrid(gridBounds, sideLen, HexagonOrientation.ANGLED, builder);
// exampleHexagonOrientation end
}
private void exampleOblong() {
// exampleOblong start
ReferencedEnvelope gridBounds = new ReferencedEnvelope(0, 100, 0, 100, null);
double width = 10.0;
double height = 5.0;
GridFeatureBuilder builder = new DefaultGridFeatureBuilder();
SimpleFeatureSource grid = Oblongs.createGrid(gridBounds, width, height, builder);
// exampleOblong end
}
private void exampleMajorMinorLines() {
// exampleMajorMinorLines start
ReferencedEnvelope gridBounds =
new ReferencedEnvelope(110.0, 150.0, -45.0, -5.0, DefaultGeographicCRS.WGS84);
/*
* Line definitions:
* major lines at 10 degree spacing are indicated by level = 2
* minor lines at 2 degree spacing are indicated by level = 1
* (level values are arbitrary; only rank order matters)
*/
List<OrthoLineDef> lineDefs =
Arrays.asList(
// vertical (longitude) lines
new OrthoLineDef(LineOrientation.VERTICAL, 2, 10.0),
new OrthoLineDef(LineOrientation.VERTICAL, 1, 2.0),
// horizontal (latitude) lines
new OrthoLineDef(LineOrientation.HORIZONTAL, 2, 10.0),
new OrthoLineDef(LineOrientation.HORIZONTAL, 1, 2.0));
// Specify vertex spacing to get "densified" polygons
double vertexSpacing = 0.1;
SimpleFeatureSource grid = Lines.createOrthoLines(gridBounds, lineDefs, vertexSpacing);
// exampleMajorMinorLines end
}
}
|
210472_0 | package org.aion.zero.impl.config;
import com.google.common.base.Objects;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.aion.log.AionLoggerFactory;
import org.slf4j.Logger;
public class CfgApiZmq {
public static final String ZMQ_KEY_DIR = "zmq_keystore";
CfgApiZmq() {
this.active = true;
this.ip = "127.0.0.1";
this.port = 8547;
this.filtersEnabled = true;
this.blockSummaryCacheEnabled = false;
this.secureConnectEnabled = false;
}
protected boolean active;
protected String ip;
protected int port;
private boolean filtersEnabled;
private boolean blockSummaryCacheEnabled;
private boolean secureConnectEnabled;
private static Logger LOG_GEN = AionLoggerFactory.getLogger("GEN");
public void fromXML(final XMLStreamReader sr) throws XMLStreamException {
this.active = Boolean.parseBoolean(sr.getAttributeValue(null, "active"));
this.ip = sr.getAttributeValue(null, "ip");
this.port = Integer.parseInt(sr.getAttributeValue(null, "port"));
// get the nested elements
loop:
while (sr.hasNext()) {
int eventType = sr.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = sr.getLocalName().toLowerCase();
switch (elementName) {
case "filters-enabled":
try {
filtersEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.filters-enabled; using preset: {}\n {}"
+ this.filtersEnabled,
e);
e.printStackTrace();
}
break;
case "block-summary-cache":
try {
blockSummaryCacheEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.block-summary-cache; using preset: {}\n {}",
this.blockSummaryCacheEnabled,
e);
}
break;
case "secure-connect":
try {
secureConnectEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.secure-connect; using preset: {}\n {}"
+ this.secureConnectEnabled,
e);
}
break;
default:
ConfigUtil.skipElement(sr);
break;
}
break;
case XMLStreamReader.END_ELEMENT:
break loop;
}
}
sr.next();
}
String toXML() {
final XMLOutputFactory output = XMLOutputFactory.newInstance();
output.setProperty("escapeCharacters", false);
XMLStreamWriter xmlWriter;
String xml;
try {
// <rpc active="false" ip="127.0.0.1" port="8545"/>
Writer strWriter = new StringWriter();
xmlWriter = output.createXMLStreamWriter(strWriter);
xmlWriter.writeCharacters("\r\n\t\t");
xmlWriter.writeStartElement("java");
xmlWriter.writeAttribute("active", this.active ? "true" : "false");
xmlWriter.writeAttribute("ip", this.ip);
xmlWriter.writeAttribute("port", this.port + "");
xmlWriter.writeCharacters("\r\n\t\t\t");
xmlWriter.writeStartElement("secure-connect");
xmlWriter.writeCharacters(String.valueOf(this.secureConnectEnabled));
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\r\n\t\t");
xmlWriter.writeEndElement();
xml = strWriter.toString();
strWriter.flush();
strWriter.close();
xmlWriter.flush();
xmlWriter.close();
return xml;
} catch (IOException | XMLStreamException e) {
e.printStackTrace();
return "";
}
}
public void setActive(boolean active) {
this.active = active;
}
public boolean getActive() {
return this.active;
}
public String getIp() {
return this.ip;
}
public int getPort() {
return this.port;
}
public boolean isFiltersEnabled() {
return this.filtersEnabled;
}
public boolean isBlockSummaryCacheEnabled() {
return this.blockSummaryCacheEnabled;
}
public boolean isSecureConnectEnabledEnabled() {
return this.secureConnectEnabled;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CfgApiZmq cfgApiZmq = (CfgApiZmq) o;
return active == cfgApiZmq.active
&& port == cfgApiZmq.port
&& filtersEnabled == cfgApiZmq.filtersEnabled
&& blockSummaryCacheEnabled == cfgApiZmq.blockSummaryCacheEnabled
&& secureConnectEnabled == cfgApiZmq.secureConnectEnabled
&& Objects.equal(ip, cfgApiZmq.ip);
}
@Override
public int hashCode() {
return Objects.hashCode(
active, ip, port, filtersEnabled, blockSummaryCacheEnabled, secureConnectEnabled);
}
}
| aionnetwork/aion | modAionImpl/src/org/aion/zero/impl/config/CfgApiZmq.java | 1,449 | // get the nested elements | line_comment | nl | package org.aion.zero.impl.config;
import com.google.common.base.Objects;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.aion.log.AionLoggerFactory;
import org.slf4j.Logger;
public class CfgApiZmq {
public static final String ZMQ_KEY_DIR = "zmq_keystore";
CfgApiZmq() {
this.active = true;
this.ip = "127.0.0.1";
this.port = 8547;
this.filtersEnabled = true;
this.blockSummaryCacheEnabled = false;
this.secureConnectEnabled = false;
}
protected boolean active;
protected String ip;
protected int port;
private boolean filtersEnabled;
private boolean blockSummaryCacheEnabled;
private boolean secureConnectEnabled;
private static Logger LOG_GEN = AionLoggerFactory.getLogger("GEN");
public void fromXML(final XMLStreamReader sr) throws XMLStreamException {
this.active = Boolean.parseBoolean(sr.getAttributeValue(null, "active"));
this.ip = sr.getAttributeValue(null, "ip");
this.port = Integer.parseInt(sr.getAttributeValue(null, "port"));
// get the<SUF>
loop:
while (sr.hasNext()) {
int eventType = sr.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = sr.getLocalName().toLowerCase();
switch (elementName) {
case "filters-enabled":
try {
filtersEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.filters-enabled; using preset: {}\n {}"
+ this.filtersEnabled,
e);
e.printStackTrace();
}
break;
case "block-summary-cache":
try {
blockSummaryCacheEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.block-summary-cache; using preset: {}\n {}",
this.blockSummaryCacheEnabled,
e);
}
break;
case "secure-connect":
try {
secureConnectEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr));
} catch (Exception e) {
LOG_GEN.warn(
"failed to read config node: aion.api.zmq.secure-connect; using preset: {}\n {}"
+ this.secureConnectEnabled,
e);
}
break;
default:
ConfigUtil.skipElement(sr);
break;
}
break;
case XMLStreamReader.END_ELEMENT:
break loop;
}
}
sr.next();
}
String toXML() {
final XMLOutputFactory output = XMLOutputFactory.newInstance();
output.setProperty("escapeCharacters", false);
XMLStreamWriter xmlWriter;
String xml;
try {
// <rpc active="false" ip="127.0.0.1" port="8545"/>
Writer strWriter = new StringWriter();
xmlWriter = output.createXMLStreamWriter(strWriter);
xmlWriter.writeCharacters("\r\n\t\t");
xmlWriter.writeStartElement("java");
xmlWriter.writeAttribute("active", this.active ? "true" : "false");
xmlWriter.writeAttribute("ip", this.ip);
xmlWriter.writeAttribute("port", this.port + "");
xmlWriter.writeCharacters("\r\n\t\t\t");
xmlWriter.writeStartElement("secure-connect");
xmlWriter.writeCharacters(String.valueOf(this.secureConnectEnabled));
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\r\n\t\t");
xmlWriter.writeEndElement();
xml = strWriter.toString();
strWriter.flush();
strWriter.close();
xmlWriter.flush();
xmlWriter.close();
return xml;
} catch (IOException | XMLStreamException e) {
e.printStackTrace();
return "";
}
}
public void setActive(boolean active) {
this.active = active;
}
public boolean getActive() {
return this.active;
}
public String getIp() {
return this.ip;
}
public int getPort() {
return this.port;
}
public boolean isFiltersEnabled() {
return this.filtersEnabled;
}
public boolean isBlockSummaryCacheEnabled() {
return this.blockSummaryCacheEnabled;
}
public boolean isSecureConnectEnabledEnabled() {
return this.secureConnectEnabled;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CfgApiZmq cfgApiZmq = (CfgApiZmq) o;
return active == cfgApiZmq.active
&& port == cfgApiZmq.port
&& filtersEnabled == cfgApiZmq.filtersEnabled
&& blockSummaryCacheEnabled == cfgApiZmq.blockSummaryCacheEnabled
&& secureConnectEnabled == cfgApiZmq.secureConnectEnabled
&& Objects.equal(ip, cfgApiZmq.ip);
}
@Override
public int hashCode() {
return Objects.hashCode(
active, ip, port, filtersEnabled, blockSummaryCacheEnabled, secureConnectEnabled);
}
}
|
210484_11 | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate here, validate in drop item events...
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null);
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} | netizen539/civcraft | civcraft/src/com/avrgaming/civcraft/listener/BonusGoodieManager.java | 5,107 | // Cant validate here, validate in drop item events... | line_comment | nl | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate<SUF>
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null);
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} |
210484_14 | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate here, validate in drop item events...
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null);
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} | netizen539/civcraft | civcraft/src/com/avrgaming/civcraft/listener/BonusGoodieManager.java | 5,107 | // goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null); | line_comment | nl | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate here, validate in drop item events...
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null,<SUF>
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} |
210499_1 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.util.common.operatie;
/**
* Marker om aan te geven dat de gegooide exception zo dramatisch is dat het herhalen direct gestopt kan worden.
*/
public interface StopHerhalingMarker {
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-util-common/src/main/java/nl/bzk/migratiebrp/util/common/operatie/StopHerhalingMarker.java | 148 | /**
* Marker om aan te geven dat de gegooide exception zo dramatisch is dat het herhalen direct gestopt kan worden.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.util.common.operatie;
/**
* Marker om aan<SUF>*/
public interface StopHerhalingMarker {
}
|
210505_1 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.util.common.operatie;
/**
* Marker om aan te geven dat de gegooide exception zo dramatisch is dat het herhalen direct gestopt kan worden.
*/
public interface StopHerhalingMarker {
}
| MinBZK/OperatieBRP | 2016/migratie 2016-02-09/migr-util-common/src/main/java/nl/bzk/migratiebrp/util/common/operatie/StopHerhalingMarker.java | 152 | /**
* Marker om aan te geven dat de gegooide exception zo dramatisch is dat het herhalen direct gestopt kan worden.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.util.common.operatie;
/**
* Marker om aan<SUF>*/
public interface StopHerhalingMarker {
}
|
210591_69 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#APIERROR
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
<SUF>*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_70 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#AUTHFAILED
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
<SUF>*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_71 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#BADARGUMENTS
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
<SUF>*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_72 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#BADVERSION
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
<SUF>*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_73 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#CONNECTIONLOSS
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
<SUF>*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_74 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#DATAINCONSISTENCY
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
<SUF>*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_75 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#INVALIDACL
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
<SUF>*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_76 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#INVALIDCALLBACK
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
<SUF>*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_77 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#MARSHALLINGERROR
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
<SUF>*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_78 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NOAUTH
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
<SUF>*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_79 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NEWCONFIGNOQUORUM
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
<SUF>*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_80 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#RECONFIGINPROGRESS
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
<SUF>*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_81 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NOCHILDRENFOREPHEMERALS
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
<SUF>*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_82 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NODEEXISTS
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
<SUF>*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_83 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NONODE
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
<SUF>*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_84 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NOTEMPTY
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
<SUF>*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_85 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#OPERATIONTIMEOUT
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
<SUF>*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_86 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#RUNTIMEINCONSISTENCY
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
<SUF>*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_87 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#SESSIONEXPIRED
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
<SUF>*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_88 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#UNKNOWNSESSION
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
<SUF>*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_89 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#SESSIONMOVED
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
<SUF>*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
210591_90 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#NOTREADONLY
*/ | block_comment | nl | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
<SUF>*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|