file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
56972_9 | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
* Copyright (C) 2018 e-Contract.be BVBA.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van
* inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19"),
/**
* I. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_I("20"),
/**
* J. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_J("21");
private final int key;
private DocumentType(final String value) {
this.key = toKey(value);
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
final int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: " + encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
final DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
| stombeur/commons-eid | commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java | 1,304 | /**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/ | block_comment | nl | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
* Copyright (C) 2018 e-Contract.be BVBA.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van
* inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van<SUF>*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19"),
/**
* I. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_I("20"),
/**
* J. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_J("21");
private final int key;
private DocumentType(final String value) {
this.key = toKey(value);
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
final int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: " + encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
final DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
|
32812_1 | /* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package com.ib.client;
import java.io.IOException;
import java.util.ArrayList;
public class EOrderDecoder {
private final EDecoder m_eDecoder;
private final Contract m_contract;
private final Order m_order;
private final OrderState m_orderState;
private final int m_version;
private final int m_serverVersion;
EOrderDecoder(EDecoder eDecoder, Contract contract, Order order, OrderState orderState, int version, int serverVersion) {
m_eDecoder = eDecoder;
m_contract = contract;
m_order = order;
m_orderState = orderState;
m_version = version;
m_serverVersion = serverVersion;
}
public void readOrderId() throws IOException {
m_order.orderId(m_eDecoder.readInt());
}
public void readContractFields() throws IOException {
if ( m_version >= 17) {
m_contract.conid(m_eDecoder.readInt());
}
m_contract.symbol(m_eDecoder.readStr());
m_contract.secType(m_eDecoder.readStr());
m_contract.lastTradeDateOrContractMonth(m_eDecoder.readStr());
m_contract.strike(m_eDecoder.readDouble());
m_contract.right(m_eDecoder.readStr());
if ( m_version >= 32) {
m_contract.multiplier(m_eDecoder.readStr());
}
m_contract.exchange(m_eDecoder.readStr());
m_contract.currency(m_eDecoder.readStr());
if ( m_version >= 2 ) {
m_contract.localSymbol(m_eDecoder.readStr());
}
if ( m_version >= 32) {
m_contract.tradingClass(m_eDecoder.readStr());
}
}
public void readAction() throws IOException {
m_order.action(m_eDecoder.readStr());
}
public void readTotalQuantity() throws IOException {
m_order.totalQuantity(m_eDecoder.readDecimal());
}
public void readOrderType() throws IOException {
m_order.orderType(m_eDecoder.readStr());
}
public void readLmtPrice() throws IOException {
if (m_version < 29) {
m_order.lmtPrice(m_eDecoder.readDouble());
}
else {
m_order.lmtPrice(m_eDecoder.readDoubleMax());
}
}
public void readAuxPrice() throws IOException {
if (m_version < 30) {
m_order.auxPrice(m_eDecoder.readDouble());
}
else {
m_order.auxPrice(m_eDecoder.readDoubleMax());
}
}
public void readTIF() throws IOException {
m_order.tif(m_eDecoder.readStr());
}
public void readOcaGroup() throws IOException {
m_order.ocaGroup(m_eDecoder.readStr());
}
public void readAccount() throws IOException {
m_order.account(m_eDecoder.readStr());
}
public void readOpenClose() throws IOException {
m_order.openClose(m_eDecoder.readStr());
}
public void readOrigin() throws IOException {
m_order.origin(m_eDecoder.readInt());
}
public void readOrderRef() throws IOException {
m_order.orderRef(m_eDecoder.readStr());
}
public void readClientId() throws IOException {
if(m_version >= 3) {
m_order.clientId(m_eDecoder.readInt());
}
}
public void readPermId() throws IOException {
if( m_version >= 4 ) {
m_order.permId(m_eDecoder.readInt());
}
}
public void readOutsideRth() throws IOException {
if( m_version >= 4 ) {
if ( m_version < 18) {
// will never happen
/* order.m_ignoreRth = */ m_eDecoder.readBoolFromInt();
}
else {
m_order.outsideRth(m_eDecoder.readBoolFromInt());
}
}
}
public void readHidden() throws IOException {
if( m_version >= 4 ) {
m_order.hidden(m_eDecoder.readInt() == 1);
}
}
public void readDiscretionaryAmount() throws IOException {
if( m_version >= 4 ) {
m_order.discretionaryAmt(m_eDecoder.readDouble());
}
}
public void readGoodAfterTime() throws IOException {
if ( m_version >= 5 ) {
m_order.goodAfterTime(m_eDecoder.readStr());
}
}
public void skipSharesAllocation() throws IOException {
if ( m_version >= 6 ) {
// skip deprecated sharesAllocation field
m_eDecoder.readStr();
}
}
public void readFAParams() throws IOException {
if ( m_version >= 7 ) {
m_order.faGroup(m_eDecoder.readStr());
m_order.faMethod(m_eDecoder.readStr());
m_order.faPercentage(m_eDecoder.readStr());
m_order.faProfile(m_eDecoder.readStr());
}
}
public void readModelCode() throws IOException {
if ( m_serverVersion >= EClient.MIN_SERVER_VER_MODELS_SUPPORT) {
m_order.modelCode(m_eDecoder.readStr());
}
}
public void readGoodTillDate() throws IOException {
if ( m_version >= 8 ) {
m_order.goodTillDate(m_eDecoder.readStr());
}
}
public void readRule80A() throws IOException {
if ( m_version >= 9) {
m_order.rule80A(m_eDecoder.readStr());
}
}
public void readPercentOffset() throws IOException {
if ( m_version >= 9) {
m_order.percentOffset(m_eDecoder.readDoubleMax());
}
}
public void readSettlingFirm() throws IOException {
if ( m_version >= 9) {
m_order.settlingFirm(m_eDecoder.readStr());
}
}
public void readShortSaleParams() throws IOException {
if ( m_version >= 9) {
m_order.shortSaleSlot(m_eDecoder.readInt());
m_order.designatedLocation(m_eDecoder.readStr());
if ( m_serverVersion == 51){
m_eDecoder.readInt(); // exemptCode
}
else if ( m_version >= 23){
m_order.exemptCode(m_eDecoder.readInt());
}
}
}
public void readAuctionStrategy() throws IOException {
if ( m_version >= 9) {
m_order.auctionStrategy(m_eDecoder.readInt());
}
}
public void readBoxOrderParams() throws IOException {
if ( m_version >= 9) {
m_order.startingPrice(m_eDecoder.readDoubleMax());
m_order.stockRefPrice(m_eDecoder.readDoubleMax());
m_order.delta(m_eDecoder.readDoubleMax());
}
}
public void readPegToStkOrVolOrderParams() throws IOException {
if ( m_version >= 9) {
m_order.stockRangeLower(m_eDecoder.readDoubleMax());
m_order.stockRangeUpper(m_eDecoder.readDoubleMax());
}
}
public void readDisplaySize() throws IOException {
if ( m_version >= 9) {
m_order.displaySize(m_eDecoder.readIntMax());
}
}
public void readOldStyleOutsideRth() throws IOException {
if ( m_version >= 9) {
if ( m_version < 18) {
// will never happen
/* order.m_rthOnly = */ m_eDecoder.readBoolFromInt();
}
}
}
public void readBlockOrder() throws IOException {
if ( m_version >= 9) {
m_order.blockOrder(m_eDecoder.readBoolFromInt());
}
}
public void readSweepToFill() throws IOException {
if ( m_version >= 9) {
m_order.sweepToFill(m_eDecoder.readBoolFromInt());
}
}
public void readAllOrNone() throws IOException {
if ( m_version >= 9) {
m_order.allOrNone(m_eDecoder.readBoolFromInt());
}
}
public void readMinQty() throws IOException {
if ( m_version >= 9) {
m_order.minQty(m_eDecoder.readIntMax());
}
}
public void readOcaType() throws IOException {
if ( m_version >= 9) {
m_order.ocaType(m_eDecoder.readInt());
}
}
public void readETradeOnly() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readBoolFromInt();
}
}
public void readFirmQuoteOnly() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readBoolFromInt();
}
}
public void readNbboPriceCap() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readDoubleMax();
}
}
public void readParentId() throws IOException {
if ( m_version >= 10) {
m_order.parentId(m_eDecoder.readInt());
}
}
public void readTriggerMethod() throws IOException {
if ( m_version >= 10) {
m_order.triggerMethod(m_eDecoder.readInt());
}
}
public void readVolOrderParams(boolean readOpenOrderAttribs) throws IOException {
if (m_version >= 11) {
m_order.volatility(m_eDecoder.readDoubleMax());
m_order.volatilityType(m_eDecoder.readInt());
if (m_version == 11) {
int receivedInt = m_eDecoder.readInt();
m_order.deltaNeutralOrderType( (receivedInt == 0) ? "NONE" : "MKT" );
} else {
m_order.deltaNeutralOrderType(m_eDecoder.readStr());
m_order.deltaNeutralAuxPrice(m_eDecoder.readDoubleMax());
if (m_version >= 27 && !Util.StringIsEmpty(m_order.getDeltaNeutralOrderType())) {
m_order.deltaNeutralConId(m_eDecoder.readInt());
if (readOpenOrderAttribs) {
m_order.deltaNeutralSettlingFirm(m_eDecoder.readStr());
m_order.deltaNeutralClearingAccount(m_eDecoder.readStr());
m_order.deltaNeutralClearingIntent(m_eDecoder.readStr());
}
}
if (m_version >= 31 && !Util.StringIsEmpty(m_order.getDeltaNeutralOrderType())) {
if (readOpenOrderAttribs) {
m_order.deltaNeutralOpenClose(m_eDecoder.readStr());
}
m_order.deltaNeutralShortSale(m_eDecoder.readBoolFromInt());
m_order.deltaNeutralShortSaleSlot(m_eDecoder.readInt());
m_order.deltaNeutralDesignatedLocation(m_eDecoder.readStr());
}
}
m_order.continuousUpdate(m_eDecoder.readInt());
if (m_serverVersion == 26) {
m_order.stockRangeLower(m_eDecoder.readDouble());
m_order.stockRangeUpper(m_eDecoder.readDouble());
}
m_order.referencePriceType(m_eDecoder.readInt());
}
}
public void readTrailParams() throws IOException {
if (m_version >= 13) {
m_order.trailStopPrice(m_eDecoder.readDoubleMax());
}
if (m_version >= 30) {
m_order.trailingPercent(m_eDecoder.readDoubleMax());
}
}
public void readBasisPoints() throws IOException {
if (m_version >= 14) {
m_order.basisPoints(m_eDecoder.readDoubleMax());
m_order.basisPointsType(m_eDecoder.readIntMax());
}
}
public void readComboLegs() throws IOException {
if (m_version >= 14) {
m_contract.comboLegsDescrip(m_eDecoder.readStr());
}
if (m_version >= 29) {
int comboLegsCount = m_eDecoder.readInt();
if (comboLegsCount > 0) {
m_contract.comboLegs(new ArrayList<>(comboLegsCount));
for (int i = 0; i < comboLegsCount; ++i) {
int conId = m_eDecoder.readInt();
int ratio = m_eDecoder.readInt();
String action = m_eDecoder.readStr();
String exchange = m_eDecoder.readStr();
int openClose = m_eDecoder.readInt();
int shortSaleSlot = m_eDecoder.readInt();
String designatedLocation = m_eDecoder.readStr();
int exemptCode = m_eDecoder.readInt();
ComboLeg comboLeg = new ComboLeg(conId, ratio, action, exchange, openClose,
shortSaleSlot, designatedLocation, exemptCode);
m_contract.comboLegs().add(comboLeg);
}
}
int orderComboLegsCount = m_eDecoder.readInt();
if (orderComboLegsCount > 0) {
m_order.orderComboLegs(new ArrayList<>(orderComboLegsCount));
for (int i = 0; i < orderComboLegsCount; ++i) {
double price = m_eDecoder.readDoubleMax();
OrderComboLeg orderComboLeg = new OrderComboLeg(price);
m_order.orderComboLegs().add(orderComboLeg);
}
}
}
}
public void readSmartComboRoutingParams() throws IOException {
if (m_version >= 26) {
int smartComboRoutingParamsCount = m_eDecoder.readInt();
if (smartComboRoutingParamsCount > 0) {
m_order.smartComboRoutingParams(new ArrayList<>(smartComboRoutingParamsCount));
for (int i = 0; i < smartComboRoutingParamsCount; ++i) {
TagValue tagValue = new TagValue();
tagValue.m_tag = m_eDecoder.readStr();
tagValue.m_value = m_eDecoder.readStr();
m_order.smartComboRoutingParams().add(tagValue);
}
}
}
}
public void readScaleOrderParams() throws IOException {
if (m_version >= 15) {
if (m_version >= 20) {
m_order.scaleInitLevelSize(m_eDecoder.readIntMax());
m_order.scaleSubsLevelSize(m_eDecoder.readIntMax());
}
else {
/* int notSuppScaleNumComponents = */ m_eDecoder.readIntMax();
m_order.scaleInitLevelSize(m_eDecoder.readIntMax());
}
m_order.scalePriceIncrement(m_eDecoder.readDoubleMax());
}
if (m_version >= 28 && m_order.scalePriceIncrement() > 0.0 && m_order.scalePriceIncrement() != Double.MAX_VALUE) {
m_order.scalePriceAdjustValue(m_eDecoder.readDoubleMax());
m_order.scalePriceAdjustInterval(m_eDecoder.readIntMax());
m_order.scaleProfitOffset(m_eDecoder.readDoubleMax());
m_order.scaleAutoReset(m_eDecoder.readBoolFromInt());
m_order.scaleInitPosition(m_eDecoder.readIntMax());
m_order.scaleInitFillQty(m_eDecoder.readIntMax());
m_order.scaleRandomPercent(m_eDecoder.readBoolFromInt());
}
}
public void readHedgeParams() throws IOException {
if (m_version >= 24) {
m_order.hedgeType(m_eDecoder.readStr());
if (!Util.StringIsEmpty(m_order.getHedgeType())) {
m_order.hedgeParam(m_eDecoder.readStr());
}
}
}
public void readOptOutSmartRouting() throws IOException {
if (m_version >= 25) {
m_order.optOutSmartRouting(m_eDecoder.readBoolFromInt());
}
}
public void readClearingParams() throws IOException {
if (m_version >= 19) {
m_order.clearingAccount(m_eDecoder.readStr());
m_order.clearingIntent(m_eDecoder.readStr());
}
}
public void readNotHeld() throws IOException {
if (m_version >= 22) {
m_order.notHeld(m_eDecoder.readBoolFromInt());
}
}
public void readDeltaNeutral() throws IOException {
if (m_version >= 20) {
if (m_eDecoder.readBoolFromInt()) {
DeltaNeutralContract deltaNeutralContract = new DeltaNeutralContract();
deltaNeutralContract.conid(m_eDecoder.readInt());
deltaNeutralContract.delta(m_eDecoder.readDouble());
deltaNeutralContract.price(m_eDecoder.readDouble());
m_contract.deltaNeutralContract(deltaNeutralContract);
}
}
}
public void readAlgoParams() throws IOException {
if (m_version >= 21) {
m_order.algoStrategy(m_eDecoder.readStr());
if (!Util.StringIsEmpty(m_order.getAlgoStrategy())) {
int algoParamsCount = m_eDecoder.readInt();
if (algoParamsCount > 0) {
for (int i = 0; i < algoParamsCount; ++i) {
TagValue tagValue = new TagValue();
tagValue.m_tag = m_eDecoder.readStr();
tagValue.m_value = m_eDecoder.readStr();
m_order.algoParams().add(tagValue);
}
}
}
}
}
public void readSolicited() throws IOException {
if (m_version >= 33) {
m_order.solicited(m_eDecoder.readBoolFromInt());
}
}
public void readWhatIfInfoAndCommission() throws IOException {
if (m_version >= 16) {
m_order.whatIf(m_eDecoder.readBoolFromInt());
readOrderStatus();
if (m_serverVersion >= EClient.MIN_SERVER_VER_WHAT_IF_EXT_FIELDS) {
m_orderState.initMarginBefore(m_eDecoder.readStr());
m_orderState.maintMarginBefore(m_eDecoder.readStr());
m_orderState.equityWithLoanBefore(m_eDecoder.readStr());
m_orderState.initMarginChange(m_eDecoder.readStr());
m_orderState.maintMarginChange(m_eDecoder.readStr());
m_orderState.equityWithLoanChange(m_eDecoder.readStr());
}
m_orderState.initMarginAfter(m_eDecoder.readStr());
m_orderState.maintMarginAfter(m_eDecoder.readStr());
m_orderState.equityWithLoanAfter(m_eDecoder.readStr());
m_orderState.commission(m_eDecoder.readDoubleMax());
m_orderState.minCommission(m_eDecoder.readDoubleMax());
m_orderState.maxCommission(m_eDecoder.readDoubleMax());
m_orderState.commissionCurrency(m_eDecoder.readStr());
m_orderState.warningText(m_eDecoder.readStr());
}
}
public void readOrderStatus() throws IOException {
m_orderState.status(m_eDecoder.readStr());
}
public void readVolRandomizeFlags() throws IOException {
if (m_version >= 34) {
m_order.randomizeSize(m_eDecoder.readBoolFromInt());
m_order.randomizePrice(m_eDecoder.readBoolFromInt());
}
}
public void readPegToBenchParams() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
if (m_order.orderType() == OrderType.PEG_BENCH) {
m_order.referenceContractId(m_eDecoder.readInt());
m_order.isPeggedChangeAmountDecrease(m_eDecoder.readBoolFromInt());
m_order.peggedChangeAmount(m_eDecoder.readDouble());
m_order.referenceChangeAmount(m_eDecoder.readDouble());
m_order.referenceExchangeId(m_eDecoder.readStr());
}
}
}
public void readConditions() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
int nConditions = m_eDecoder.readInt();
if (nConditions > 0) {
for (int i = 0; i < nConditions; i++) {
OrderConditionType orderConditionType = OrderConditionType.fromInt(m_eDecoder.readInt());
OrderCondition condition = OrderCondition.create(orderConditionType);
condition.readFrom(m_eDecoder);
m_order.conditions().add(condition);
}
m_order.conditionsIgnoreRth(m_eDecoder.readBoolFromInt());
m_order.conditionsCancelOrder(m_eDecoder.readBoolFromInt());
}
}
}
public void readAdjustedOrderParams() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
m_order.adjustedOrderType(OrderType.get(m_eDecoder.readStr()));
m_order.triggerPrice(m_eDecoder.readDoubleMax());
readStopPriceAndLmtPriceOffset();
m_order.adjustedStopPrice(m_eDecoder.readDoubleMax());
m_order.adjustedStopLimitPrice(m_eDecoder.readDoubleMax());
m_order.adjustedTrailingAmount(m_eDecoder.readDoubleMax());
m_order.adjustableTrailingUnit(m_eDecoder.readInt());
}
}
public void readStopPriceAndLmtPriceOffset() throws IOException {
m_order.trailStopPrice(m_eDecoder.readDoubleMax());
m_order.lmtPriceOffset(m_eDecoder.readDoubleMax());
}
public void readSoftDollarTier() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_SOFT_DOLLAR_TIER) {
m_order.softDollarTier(new SoftDollarTier(m_eDecoder.readStr(), m_eDecoder.readStr(), m_eDecoder.readStr()));
}
}
public void readCashQty() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_CASH_QTY) {
m_order.cashQty(m_eDecoder.readDoubleMax());
}
}
public void readDontUseAutoPriceForHedge() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_AUTO_PRICE_FOR_HEDGE) {
m_order.dontUseAutoPriceForHedge(m_eDecoder.readBoolFromInt());
}
}
public void readIsOmsContainer() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_ORDER_CONTAINER) {
m_order.isOmsContainer(m_eDecoder.readBoolFromInt());
}
}
public void readDiscretionaryUpToLimitPrice() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_D_PEG_ORDERS) {
m_order.discretionaryUpToLimitPrice(m_eDecoder.readBoolFromInt());
}
}
public void readAutoCancelDate() throws IOException {
m_order.autoCancelDate(m_eDecoder.readStr());
}
public void readFilledQuantity() throws IOException {
m_order.filledQuantity(m_eDecoder.readDecimal());
}
public void readRefFuturesConId() throws IOException {
m_order.refFuturesConId(m_eDecoder.readInt());
}
public void readAutoCancelParent() throws IOException {
readAutoCancelParent(EClient.MIN_VERSION);
}
public void readAutoCancelParent(int minVersionAutoCancelParent) throws IOException {
if (m_serverVersion >= minVersionAutoCancelParent) {
m_order.autoCancelParent(m_eDecoder.readBoolFromInt());
}
}
public void readShareholder() throws IOException {
m_order.shareholder(m_eDecoder.readStr());
}
public void readImbalanceOnly() throws IOException {
m_order.imbalanceOnly(m_eDecoder.readBoolFromInt());
}
public void readRouteMarketableToBbo() throws IOException {
m_order.routeMarketableToBbo(m_eDecoder.readBoolFromInt());
}
public void readParentPermId() throws IOException {
m_order.parentPermId(m_eDecoder.readLong());
}
public void readCompletedTime() throws IOException {
m_orderState.completedTime(m_eDecoder.readStr());
}
public void readCompletedStatus() throws IOException {
m_orderState.completedStatus(m_eDecoder.readStr());
}
public void readUsePriceMgmtAlgo() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PRICE_MGMT_ALGO) {
m_order.usePriceMgmtAlgo(m_eDecoder.readBoolFromInt());
}
}
public void readDuration() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_DURATION) {
m_order.duration(m_eDecoder.readInt());
}
}
public void readPostToAts() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_POST_TO_ATS) {
m_order.postToAts(m_eDecoder.readIntMax());
}
}
public void readPegBestPegMidOrderAttributes() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGBEST_PEGMID_OFFSETS) {
m_order.minTradeQty(m_eDecoder.readIntMax());
m_order.minCompeteSize(m_eDecoder.readIntMax());
m_order.competeAgainstBestOffset(m_eDecoder.readDoubleMax());
m_order.midOffsetAtWhole(m_eDecoder.readDoubleMax());
m_order.midOffsetAtHalf(m_eDecoder.readDoubleMax());
}
}
}
| stoqey/ib | ref/client/EOrderDecoder.java | 7,543 | // will never happen | line_comment | nl | /* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package com.ib.client;
import java.io.IOException;
import java.util.ArrayList;
public class EOrderDecoder {
private final EDecoder m_eDecoder;
private final Contract m_contract;
private final Order m_order;
private final OrderState m_orderState;
private final int m_version;
private final int m_serverVersion;
EOrderDecoder(EDecoder eDecoder, Contract contract, Order order, OrderState orderState, int version, int serverVersion) {
m_eDecoder = eDecoder;
m_contract = contract;
m_order = order;
m_orderState = orderState;
m_version = version;
m_serverVersion = serverVersion;
}
public void readOrderId() throws IOException {
m_order.orderId(m_eDecoder.readInt());
}
public void readContractFields() throws IOException {
if ( m_version >= 17) {
m_contract.conid(m_eDecoder.readInt());
}
m_contract.symbol(m_eDecoder.readStr());
m_contract.secType(m_eDecoder.readStr());
m_contract.lastTradeDateOrContractMonth(m_eDecoder.readStr());
m_contract.strike(m_eDecoder.readDouble());
m_contract.right(m_eDecoder.readStr());
if ( m_version >= 32) {
m_contract.multiplier(m_eDecoder.readStr());
}
m_contract.exchange(m_eDecoder.readStr());
m_contract.currency(m_eDecoder.readStr());
if ( m_version >= 2 ) {
m_contract.localSymbol(m_eDecoder.readStr());
}
if ( m_version >= 32) {
m_contract.tradingClass(m_eDecoder.readStr());
}
}
public void readAction() throws IOException {
m_order.action(m_eDecoder.readStr());
}
public void readTotalQuantity() throws IOException {
m_order.totalQuantity(m_eDecoder.readDecimal());
}
public void readOrderType() throws IOException {
m_order.orderType(m_eDecoder.readStr());
}
public void readLmtPrice() throws IOException {
if (m_version < 29) {
m_order.lmtPrice(m_eDecoder.readDouble());
}
else {
m_order.lmtPrice(m_eDecoder.readDoubleMax());
}
}
public void readAuxPrice() throws IOException {
if (m_version < 30) {
m_order.auxPrice(m_eDecoder.readDouble());
}
else {
m_order.auxPrice(m_eDecoder.readDoubleMax());
}
}
public void readTIF() throws IOException {
m_order.tif(m_eDecoder.readStr());
}
public void readOcaGroup() throws IOException {
m_order.ocaGroup(m_eDecoder.readStr());
}
public void readAccount() throws IOException {
m_order.account(m_eDecoder.readStr());
}
public void readOpenClose() throws IOException {
m_order.openClose(m_eDecoder.readStr());
}
public void readOrigin() throws IOException {
m_order.origin(m_eDecoder.readInt());
}
public void readOrderRef() throws IOException {
m_order.orderRef(m_eDecoder.readStr());
}
public void readClientId() throws IOException {
if(m_version >= 3) {
m_order.clientId(m_eDecoder.readInt());
}
}
public void readPermId() throws IOException {
if( m_version >= 4 ) {
m_order.permId(m_eDecoder.readInt());
}
}
public void readOutsideRth() throws IOException {
if( m_version >= 4 ) {
if ( m_version < 18) {
// will never<SUF>
/* order.m_ignoreRth = */ m_eDecoder.readBoolFromInt();
}
else {
m_order.outsideRth(m_eDecoder.readBoolFromInt());
}
}
}
public void readHidden() throws IOException {
if( m_version >= 4 ) {
m_order.hidden(m_eDecoder.readInt() == 1);
}
}
public void readDiscretionaryAmount() throws IOException {
if( m_version >= 4 ) {
m_order.discretionaryAmt(m_eDecoder.readDouble());
}
}
public void readGoodAfterTime() throws IOException {
if ( m_version >= 5 ) {
m_order.goodAfterTime(m_eDecoder.readStr());
}
}
public void skipSharesAllocation() throws IOException {
if ( m_version >= 6 ) {
// skip deprecated sharesAllocation field
m_eDecoder.readStr();
}
}
public void readFAParams() throws IOException {
if ( m_version >= 7 ) {
m_order.faGroup(m_eDecoder.readStr());
m_order.faMethod(m_eDecoder.readStr());
m_order.faPercentage(m_eDecoder.readStr());
m_order.faProfile(m_eDecoder.readStr());
}
}
public void readModelCode() throws IOException {
if ( m_serverVersion >= EClient.MIN_SERVER_VER_MODELS_SUPPORT) {
m_order.modelCode(m_eDecoder.readStr());
}
}
public void readGoodTillDate() throws IOException {
if ( m_version >= 8 ) {
m_order.goodTillDate(m_eDecoder.readStr());
}
}
public void readRule80A() throws IOException {
if ( m_version >= 9) {
m_order.rule80A(m_eDecoder.readStr());
}
}
public void readPercentOffset() throws IOException {
if ( m_version >= 9) {
m_order.percentOffset(m_eDecoder.readDoubleMax());
}
}
public void readSettlingFirm() throws IOException {
if ( m_version >= 9) {
m_order.settlingFirm(m_eDecoder.readStr());
}
}
public void readShortSaleParams() throws IOException {
if ( m_version >= 9) {
m_order.shortSaleSlot(m_eDecoder.readInt());
m_order.designatedLocation(m_eDecoder.readStr());
if ( m_serverVersion == 51){
m_eDecoder.readInt(); // exemptCode
}
else if ( m_version >= 23){
m_order.exemptCode(m_eDecoder.readInt());
}
}
}
public void readAuctionStrategy() throws IOException {
if ( m_version >= 9) {
m_order.auctionStrategy(m_eDecoder.readInt());
}
}
public void readBoxOrderParams() throws IOException {
if ( m_version >= 9) {
m_order.startingPrice(m_eDecoder.readDoubleMax());
m_order.stockRefPrice(m_eDecoder.readDoubleMax());
m_order.delta(m_eDecoder.readDoubleMax());
}
}
public void readPegToStkOrVolOrderParams() throws IOException {
if ( m_version >= 9) {
m_order.stockRangeLower(m_eDecoder.readDoubleMax());
m_order.stockRangeUpper(m_eDecoder.readDoubleMax());
}
}
public void readDisplaySize() throws IOException {
if ( m_version >= 9) {
m_order.displaySize(m_eDecoder.readIntMax());
}
}
public void readOldStyleOutsideRth() throws IOException {
if ( m_version >= 9) {
if ( m_version < 18) {
// will never happen
/* order.m_rthOnly = */ m_eDecoder.readBoolFromInt();
}
}
}
public void readBlockOrder() throws IOException {
if ( m_version >= 9) {
m_order.blockOrder(m_eDecoder.readBoolFromInt());
}
}
public void readSweepToFill() throws IOException {
if ( m_version >= 9) {
m_order.sweepToFill(m_eDecoder.readBoolFromInt());
}
}
public void readAllOrNone() throws IOException {
if ( m_version >= 9) {
m_order.allOrNone(m_eDecoder.readBoolFromInt());
}
}
public void readMinQty() throws IOException {
if ( m_version >= 9) {
m_order.minQty(m_eDecoder.readIntMax());
}
}
public void readOcaType() throws IOException {
if ( m_version >= 9) {
m_order.ocaType(m_eDecoder.readInt());
}
}
public void readETradeOnly() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readBoolFromInt();
}
}
public void readFirmQuoteOnly() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readBoolFromInt();
}
}
public void readNbboPriceCap() throws IOException {
if ( m_version >= 9) {
// skip deprecated field
m_eDecoder.readDoubleMax();
}
}
public void readParentId() throws IOException {
if ( m_version >= 10) {
m_order.parentId(m_eDecoder.readInt());
}
}
public void readTriggerMethod() throws IOException {
if ( m_version >= 10) {
m_order.triggerMethod(m_eDecoder.readInt());
}
}
public void readVolOrderParams(boolean readOpenOrderAttribs) throws IOException {
if (m_version >= 11) {
m_order.volatility(m_eDecoder.readDoubleMax());
m_order.volatilityType(m_eDecoder.readInt());
if (m_version == 11) {
int receivedInt = m_eDecoder.readInt();
m_order.deltaNeutralOrderType( (receivedInt == 0) ? "NONE" : "MKT" );
} else {
m_order.deltaNeutralOrderType(m_eDecoder.readStr());
m_order.deltaNeutralAuxPrice(m_eDecoder.readDoubleMax());
if (m_version >= 27 && !Util.StringIsEmpty(m_order.getDeltaNeutralOrderType())) {
m_order.deltaNeutralConId(m_eDecoder.readInt());
if (readOpenOrderAttribs) {
m_order.deltaNeutralSettlingFirm(m_eDecoder.readStr());
m_order.deltaNeutralClearingAccount(m_eDecoder.readStr());
m_order.deltaNeutralClearingIntent(m_eDecoder.readStr());
}
}
if (m_version >= 31 && !Util.StringIsEmpty(m_order.getDeltaNeutralOrderType())) {
if (readOpenOrderAttribs) {
m_order.deltaNeutralOpenClose(m_eDecoder.readStr());
}
m_order.deltaNeutralShortSale(m_eDecoder.readBoolFromInt());
m_order.deltaNeutralShortSaleSlot(m_eDecoder.readInt());
m_order.deltaNeutralDesignatedLocation(m_eDecoder.readStr());
}
}
m_order.continuousUpdate(m_eDecoder.readInt());
if (m_serverVersion == 26) {
m_order.stockRangeLower(m_eDecoder.readDouble());
m_order.stockRangeUpper(m_eDecoder.readDouble());
}
m_order.referencePriceType(m_eDecoder.readInt());
}
}
public void readTrailParams() throws IOException {
if (m_version >= 13) {
m_order.trailStopPrice(m_eDecoder.readDoubleMax());
}
if (m_version >= 30) {
m_order.trailingPercent(m_eDecoder.readDoubleMax());
}
}
public void readBasisPoints() throws IOException {
if (m_version >= 14) {
m_order.basisPoints(m_eDecoder.readDoubleMax());
m_order.basisPointsType(m_eDecoder.readIntMax());
}
}
public void readComboLegs() throws IOException {
if (m_version >= 14) {
m_contract.comboLegsDescrip(m_eDecoder.readStr());
}
if (m_version >= 29) {
int comboLegsCount = m_eDecoder.readInt();
if (comboLegsCount > 0) {
m_contract.comboLegs(new ArrayList<>(comboLegsCount));
for (int i = 0; i < comboLegsCount; ++i) {
int conId = m_eDecoder.readInt();
int ratio = m_eDecoder.readInt();
String action = m_eDecoder.readStr();
String exchange = m_eDecoder.readStr();
int openClose = m_eDecoder.readInt();
int shortSaleSlot = m_eDecoder.readInt();
String designatedLocation = m_eDecoder.readStr();
int exemptCode = m_eDecoder.readInt();
ComboLeg comboLeg = new ComboLeg(conId, ratio, action, exchange, openClose,
shortSaleSlot, designatedLocation, exemptCode);
m_contract.comboLegs().add(comboLeg);
}
}
int orderComboLegsCount = m_eDecoder.readInt();
if (orderComboLegsCount > 0) {
m_order.orderComboLegs(new ArrayList<>(orderComboLegsCount));
for (int i = 0; i < orderComboLegsCount; ++i) {
double price = m_eDecoder.readDoubleMax();
OrderComboLeg orderComboLeg = new OrderComboLeg(price);
m_order.orderComboLegs().add(orderComboLeg);
}
}
}
}
public void readSmartComboRoutingParams() throws IOException {
if (m_version >= 26) {
int smartComboRoutingParamsCount = m_eDecoder.readInt();
if (smartComboRoutingParamsCount > 0) {
m_order.smartComboRoutingParams(new ArrayList<>(smartComboRoutingParamsCount));
for (int i = 0; i < smartComboRoutingParamsCount; ++i) {
TagValue tagValue = new TagValue();
tagValue.m_tag = m_eDecoder.readStr();
tagValue.m_value = m_eDecoder.readStr();
m_order.smartComboRoutingParams().add(tagValue);
}
}
}
}
public void readScaleOrderParams() throws IOException {
if (m_version >= 15) {
if (m_version >= 20) {
m_order.scaleInitLevelSize(m_eDecoder.readIntMax());
m_order.scaleSubsLevelSize(m_eDecoder.readIntMax());
}
else {
/* int notSuppScaleNumComponents = */ m_eDecoder.readIntMax();
m_order.scaleInitLevelSize(m_eDecoder.readIntMax());
}
m_order.scalePriceIncrement(m_eDecoder.readDoubleMax());
}
if (m_version >= 28 && m_order.scalePriceIncrement() > 0.0 && m_order.scalePriceIncrement() != Double.MAX_VALUE) {
m_order.scalePriceAdjustValue(m_eDecoder.readDoubleMax());
m_order.scalePriceAdjustInterval(m_eDecoder.readIntMax());
m_order.scaleProfitOffset(m_eDecoder.readDoubleMax());
m_order.scaleAutoReset(m_eDecoder.readBoolFromInt());
m_order.scaleInitPosition(m_eDecoder.readIntMax());
m_order.scaleInitFillQty(m_eDecoder.readIntMax());
m_order.scaleRandomPercent(m_eDecoder.readBoolFromInt());
}
}
public void readHedgeParams() throws IOException {
if (m_version >= 24) {
m_order.hedgeType(m_eDecoder.readStr());
if (!Util.StringIsEmpty(m_order.getHedgeType())) {
m_order.hedgeParam(m_eDecoder.readStr());
}
}
}
public void readOptOutSmartRouting() throws IOException {
if (m_version >= 25) {
m_order.optOutSmartRouting(m_eDecoder.readBoolFromInt());
}
}
public void readClearingParams() throws IOException {
if (m_version >= 19) {
m_order.clearingAccount(m_eDecoder.readStr());
m_order.clearingIntent(m_eDecoder.readStr());
}
}
public void readNotHeld() throws IOException {
if (m_version >= 22) {
m_order.notHeld(m_eDecoder.readBoolFromInt());
}
}
public void readDeltaNeutral() throws IOException {
if (m_version >= 20) {
if (m_eDecoder.readBoolFromInt()) {
DeltaNeutralContract deltaNeutralContract = new DeltaNeutralContract();
deltaNeutralContract.conid(m_eDecoder.readInt());
deltaNeutralContract.delta(m_eDecoder.readDouble());
deltaNeutralContract.price(m_eDecoder.readDouble());
m_contract.deltaNeutralContract(deltaNeutralContract);
}
}
}
public void readAlgoParams() throws IOException {
if (m_version >= 21) {
m_order.algoStrategy(m_eDecoder.readStr());
if (!Util.StringIsEmpty(m_order.getAlgoStrategy())) {
int algoParamsCount = m_eDecoder.readInt();
if (algoParamsCount > 0) {
for (int i = 0; i < algoParamsCount; ++i) {
TagValue tagValue = new TagValue();
tagValue.m_tag = m_eDecoder.readStr();
tagValue.m_value = m_eDecoder.readStr();
m_order.algoParams().add(tagValue);
}
}
}
}
}
public void readSolicited() throws IOException {
if (m_version >= 33) {
m_order.solicited(m_eDecoder.readBoolFromInt());
}
}
public void readWhatIfInfoAndCommission() throws IOException {
if (m_version >= 16) {
m_order.whatIf(m_eDecoder.readBoolFromInt());
readOrderStatus();
if (m_serverVersion >= EClient.MIN_SERVER_VER_WHAT_IF_EXT_FIELDS) {
m_orderState.initMarginBefore(m_eDecoder.readStr());
m_orderState.maintMarginBefore(m_eDecoder.readStr());
m_orderState.equityWithLoanBefore(m_eDecoder.readStr());
m_orderState.initMarginChange(m_eDecoder.readStr());
m_orderState.maintMarginChange(m_eDecoder.readStr());
m_orderState.equityWithLoanChange(m_eDecoder.readStr());
}
m_orderState.initMarginAfter(m_eDecoder.readStr());
m_orderState.maintMarginAfter(m_eDecoder.readStr());
m_orderState.equityWithLoanAfter(m_eDecoder.readStr());
m_orderState.commission(m_eDecoder.readDoubleMax());
m_orderState.minCommission(m_eDecoder.readDoubleMax());
m_orderState.maxCommission(m_eDecoder.readDoubleMax());
m_orderState.commissionCurrency(m_eDecoder.readStr());
m_orderState.warningText(m_eDecoder.readStr());
}
}
public void readOrderStatus() throws IOException {
m_orderState.status(m_eDecoder.readStr());
}
public void readVolRandomizeFlags() throws IOException {
if (m_version >= 34) {
m_order.randomizeSize(m_eDecoder.readBoolFromInt());
m_order.randomizePrice(m_eDecoder.readBoolFromInt());
}
}
public void readPegToBenchParams() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
if (m_order.orderType() == OrderType.PEG_BENCH) {
m_order.referenceContractId(m_eDecoder.readInt());
m_order.isPeggedChangeAmountDecrease(m_eDecoder.readBoolFromInt());
m_order.peggedChangeAmount(m_eDecoder.readDouble());
m_order.referenceChangeAmount(m_eDecoder.readDouble());
m_order.referenceExchangeId(m_eDecoder.readStr());
}
}
}
public void readConditions() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
int nConditions = m_eDecoder.readInt();
if (nConditions > 0) {
for (int i = 0; i < nConditions; i++) {
OrderConditionType orderConditionType = OrderConditionType.fromInt(m_eDecoder.readInt());
OrderCondition condition = OrderCondition.create(orderConditionType);
condition.readFrom(m_eDecoder);
m_order.conditions().add(condition);
}
m_order.conditionsIgnoreRth(m_eDecoder.readBoolFromInt());
m_order.conditionsCancelOrder(m_eDecoder.readBoolFromInt());
}
}
}
public void readAdjustedOrderParams() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGGED_TO_BENCHMARK) {
m_order.adjustedOrderType(OrderType.get(m_eDecoder.readStr()));
m_order.triggerPrice(m_eDecoder.readDoubleMax());
readStopPriceAndLmtPriceOffset();
m_order.adjustedStopPrice(m_eDecoder.readDoubleMax());
m_order.adjustedStopLimitPrice(m_eDecoder.readDoubleMax());
m_order.adjustedTrailingAmount(m_eDecoder.readDoubleMax());
m_order.adjustableTrailingUnit(m_eDecoder.readInt());
}
}
public void readStopPriceAndLmtPriceOffset() throws IOException {
m_order.trailStopPrice(m_eDecoder.readDoubleMax());
m_order.lmtPriceOffset(m_eDecoder.readDoubleMax());
}
public void readSoftDollarTier() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_SOFT_DOLLAR_TIER) {
m_order.softDollarTier(new SoftDollarTier(m_eDecoder.readStr(), m_eDecoder.readStr(), m_eDecoder.readStr()));
}
}
public void readCashQty() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_CASH_QTY) {
m_order.cashQty(m_eDecoder.readDoubleMax());
}
}
public void readDontUseAutoPriceForHedge() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_AUTO_PRICE_FOR_HEDGE) {
m_order.dontUseAutoPriceForHedge(m_eDecoder.readBoolFromInt());
}
}
public void readIsOmsContainer() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_ORDER_CONTAINER) {
m_order.isOmsContainer(m_eDecoder.readBoolFromInt());
}
}
public void readDiscretionaryUpToLimitPrice() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_D_PEG_ORDERS) {
m_order.discretionaryUpToLimitPrice(m_eDecoder.readBoolFromInt());
}
}
public void readAutoCancelDate() throws IOException {
m_order.autoCancelDate(m_eDecoder.readStr());
}
public void readFilledQuantity() throws IOException {
m_order.filledQuantity(m_eDecoder.readDecimal());
}
public void readRefFuturesConId() throws IOException {
m_order.refFuturesConId(m_eDecoder.readInt());
}
public void readAutoCancelParent() throws IOException {
readAutoCancelParent(EClient.MIN_VERSION);
}
public void readAutoCancelParent(int minVersionAutoCancelParent) throws IOException {
if (m_serverVersion >= minVersionAutoCancelParent) {
m_order.autoCancelParent(m_eDecoder.readBoolFromInt());
}
}
public void readShareholder() throws IOException {
m_order.shareholder(m_eDecoder.readStr());
}
public void readImbalanceOnly() throws IOException {
m_order.imbalanceOnly(m_eDecoder.readBoolFromInt());
}
public void readRouteMarketableToBbo() throws IOException {
m_order.routeMarketableToBbo(m_eDecoder.readBoolFromInt());
}
public void readParentPermId() throws IOException {
m_order.parentPermId(m_eDecoder.readLong());
}
public void readCompletedTime() throws IOException {
m_orderState.completedTime(m_eDecoder.readStr());
}
public void readCompletedStatus() throws IOException {
m_orderState.completedStatus(m_eDecoder.readStr());
}
public void readUsePriceMgmtAlgo() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PRICE_MGMT_ALGO) {
m_order.usePriceMgmtAlgo(m_eDecoder.readBoolFromInt());
}
}
public void readDuration() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_DURATION) {
m_order.duration(m_eDecoder.readInt());
}
}
public void readPostToAts() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_POST_TO_ATS) {
m_order.postToAts(m_eDecoder.readIntMax());
}
}
public void readPegBestPegMidOrderAttributes() throws IOException {
if (m_serverVersion >= EClient.MIN_SERVER_VER_PEGBEST_PEGMID_OFFSETS) {
m_order.minTradeQty(m_eDecoder.readIntMax());
m_order.minCompeteSize(m_eDecoder.readIntMax());
m_order.competeAgainstBestOffset(m_eDecoder.readDoubleMax());
m_order.midOffsetAtWhole(m_eDecoder.readDoubleMax());
m_order.midOffsetAtHalf(m_eDecoder.readDoubleMax());
}
}
}
|
32073_0 | package demos.nehe.lesson14;
import demos.common.GLDisplay;
/**
* @author Pepijn Van Eeckhoudt
*/
public class Lesson14 {
public static void main(String[] args) {
GLDisplay neheGLDisplay = GLDisplay.createGLDisplay("Lesson 14: Outline fonts");
Renderer renderer = new Renderer();
neheGLDisplay.addGLEventListener(renderer);
neheGLDisplay.start();
}
}
| strange-attractors/gmilk | ProcessingGLBase/src/demos/nehe/lesson14/Lesson14.java | 135 | /**
* @author Pepijn Van Eeckhoudt
*/ | block_comment | nl | package demos.nehe.lesson14;
import demos.common.GLDisplay;
/**
* @author Pepijn Van<SUF>*/
public class Lesson14 {
public static void main(String[] args) {
GLDisplay neheGLDisplay = GLDisplay.createGLDisplay("Lesson 14: Outline fonts");
Renderer renderer = new Renderer();
neheGLDisplay.addGLEventListener(renderer);
neheGLDisplay.start();
}
}
|
60277_2 | __________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode prev = null;
public boolean isUnivalTree(TreeNode root) {
if(root == null)
return true;
if(prev != null){
if(prev.val != root.val)
return false;
}
prev = root;
if(isUnivalTree(root.left) && isUnivalTree(root.right)){
return true;
}
return false;
}
}
__________________________________________________________________________________________________
sample 35488 kb submission
// Base case root = null
// Let left be val of left node. If left node is null, left = root.val
// Let right be val of right node. If right node is null, right = root.val
// Return root.val = left && root.val == root.right && isValid(root.left) && isValid(root.right)
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) return true;
int left = (root.left == null) ? root.val : root.left.val;
int right = (root.right == null) ? root.val : root.right.val;
return root.val == left && root.val == right && isUnivalTree(root.left) && isUnivalTree(root.right);
}
}
__________________________________________________________________________________________________
| strengthen/LeetCode | Java/965.java | 425 | // Let left be val of left node. If left node is null, left = root.val | line_comment | nl | __________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode prev = null;
public boolean isUnivalTree(TreeNode root) {
if(root == null)
return true;
if(prev != null){
if(prev.val != root.val)
return false;
}
prev = root;
if(isUnivalTree(root.left) && isUnivalTree(root.right)){
return true;
}
return false;
}
}
__________________________________________________________________________________________________
sample 35488 kb submission
// Base case root = null
// Let left<SUF>
// Let right be val of right node. If right node is null, right = root.val
// Return root.val = left && root.val == root.right && isValid(root.left) && isValid(root.right)
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) return true;
int left = (root.left == null) ? root.val : root.left.val;
int right = (root.right == null) ? root.val : root.right.val;
return root.val == left && root.val == right && isUnivalTree(root.left) && isUnivalTree(root.right);
}
}
__________________________________________________________________________________________________
|
16550_6 | /*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.model;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationOAuth;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationPlain;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationScram;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationScramSha256;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationTls;
import io.strimzi.api.kafka.model.common.tracing.JaegerTracing;
import io.strimzi.api.kafka.model.common.tracing.OpenTelemetryTracing;
import io.strimzi.api.kafka.model.common.tracing.Tracing;
import io.strimzi.api.kafka.model.connector.KafkaConnector;
import io.strimzi.api.kafka.model.connector.KafkaConnectorBuilder;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2ClusterSpec;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2ConnectorSpec;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2MirrorSpec;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.ReconciliationLogger;
import io.strimzi.operator.common.model.InvalidResourceException;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.SslConfigs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Kafka Mirror Maker 2 Connectors model
*/
public class KafkaMirrorMaker2Connectors {
private static final ReconciliationLogger LOGGER = ReconciliationLogger.create(KafkaMirrorMaker2Connectors.class.getName());
private static final String CONNECTOR_JAVA_PACKAGE = "org.apache.kafka.connect.mirror";
private static final String TARGET_CLUSTER_PREFIX = "target.cluster.";
private static final String SOURCE_CLUSTER_PREFIX = "source.cluster.";
private static final String STORE_LOCATION_ROOT = "/tmp/kafka/clusters/";
private static final String TRUSTSTORE_SUFFIX = ".truststore.p12";
private static final String KEYSTORE_SUFFIX = ".keystore.p12";
private static final String CONNECT_CONFIG_FILE = "/tmp/strimzi-connect.properties";
private static final String CONNECTORS_CONFIG_FILE = "/tmp/strimzi-mirrormaker2-connector.properties";
private static final String SOURCE_CONNECTOR_SUFFIX = ".MirrorSourceConnector";
private static final String CHECKPOINT_CONNECTOR_SUFFIX = ".MirrorCheckpointConnector";
private static final String HEARTBEAT_CONNECTOR_SUFFIX = ".MirrorHeartbeatConnector";
private static final Map<String, Function<KafkaMirrorMaker2MirrorSpec, KafkaMirrorMaker2ConnectorSpec>> CONNECTORS = Map.of(
SOURCE_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getSourceConnector,
CHECKPOINT_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getCheckpointConnector,
HEARTBEAT_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getHeartbeatConnector
);
private final Reconciliation reconciliation;
private final Map<String, KafkaMirrorMaker2ClusterSpec> clusters;
private final List<KafkaMirrorMaker2MirrorSpec> mirrors;
private final Tracing tracing;
private final boolean rackAwarenessEnabled;
/**
* Constructor
*
* @param reconciliation Reconciliation marker
* @param kafkaMirrorMaker2 KafkaMirrorMaker2 custom resource
*/
private KafkaMirrorMaker2Connectors(Reconciliation reconciliation, KafkaMirrorMaker2 kafkaMirrorMaker2) {
this.reconciliation = reconciliation;
this.clusters = kafkaMirrorMaker2.getSpec().getClusters().stream().collect(Collectors.toMap(KafkaMirrorMaker2ClusterSpec::getAlias, Function.identity()));
this.mirrors = kafkaMirrorMaker2.getSpec().getMirrors();
this.tracing = kafkaMirrorMaker2.getSpec().getTracing();
this.rackAwarenessEnabled = kafkaMirrorMaker2.getSpec().getRack() != null;
}
/**
* Creates and returns a Mirror Maker 2 Connectors instance
*
* @param reconciliation Reconciliation marker
* @param kafkaMirrorMaker2 KafkaMirrorMaker2 custom resource
*
* @return Newly created KafkaMirrorMaker2Connectors instance
*/
public static KafkaMirrorMaker2Connectors fromCrd(Reconciliation reconciliation, KafkaMirrorMaker2 kafkaMirrorMaker2) {
validateConnectors(kafkaMirrorMaker2);
return new KafkaMirrorMaker2Connectors(reconciliation, kafkaMirrorMaker2);
}
/* test */ static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) {
if (kafkaMirrorMaker2.getSpec() == null) {
throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource");
} else {
if (kafkaMirrorMaker2.getSpec().getClusters() == null || kafkaMirrorMaker2.getSpec().getMirrors() == null) {
throw new InvalidResourceException(".spec.clusters and .spec.mirrors sections are required in KafkaMirrorMaker2 resource");
} else {
Set<String> existingClusterAliases = kafkaMirrorMaker2.getSpec().getClusters().stream().map(KafkaMirrorMaker2ClusterSpec::getAlias).collect(Collectors.toSet());
Set<String> errorMessages = new HashSet<>();
String connectCluster = kafkaMirrorMaker2.getSpec().getConnectCluster();
for (KafkaMirrorMaker2MirrorSpec mirror : kafkaMirrorMaker2.getSpec().getMirrors()) {
if (mirror.getSourceCluster() == null) {
errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the source cluster alias");
} else if (!existingClusterAliases.contains(mirror.getSourceCluster())) {
errorMessages.add("Source cluster alias " + mirror.getSourceCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions");
}
if (mirror.getTargetCluster() == null) {
errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the target cluster alias");
} else if (!existingClusterAliases.contains(mirror.getTargetCluster())) {
errorMessages.add("Target cluster alias " + mirror.getTargetCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions");
}
if (!mirror.getTargetCluster().equals(connectCluster)) {
errorMessages.add("Connect cluster alias (currently set to " + connectCluster + ") has to be the same as the target cluster alias " + mirror.getTargetCluster());
}
}
if (!errorMessages.isEmpty()) {
throw new InvalidResourceException("KafkaMirrorMaker2 resource validation failed: " + errorMessages);
}
}
}
}
/**
* @return List with connector definitions for this Mirror Maker 2 cluster
*/
public List<KafkaConnector> generateConnectorDefinitions() {
List<KafkaConnector> connectors = new ArrayList<>();
for (KafkaMirrorMaker2MirrorSpec mirror : mirrors) {
for (Entry<String, Function<KafkaMirrorMaker2MirrorSpec, KafkaMirrorMaker2ConnectorSpec>> connectorType : CONNECTORS.entrySet()) {
// Get the connector spec from the MM2 CR definitions
KafkaMirrorMaker2ConnectorSpec mm2ConnectorSpec = connectorType.getValue().apply(mirror);
if (mm2ConnectorSpec != null) {
@SuppressWarnings("deprecation") // getPause() is deprecated
KafkaConnector connector = new KafkaConnectorBuilder()
.withNewMetadata()
.withName(mirror.getSourceCluster() + "->" + mirror.getTargetCluster() + connectorType.getKey())
.endMetadata()
.withNewSpec()
.withClassName(CONNECTOR_JAVA_PACKAGE + connectorType.getKey())
.withConfig(prepareMirrorMaker2ConnectorConfig(mirror, mm2ConnectorSpec, clusters.get(mirror.getSourceCluster()), clusters.get(mirror.getTargetCluster())))
.withPause(mm2ConnectorSpec.getPause())
.withState(mm2ConnectorSpec.getState())
.withAutoRestart(mm2ConnectorSpec.getAutoRestart())
.withTasksMax(mm2ConnectorSpec.getTasksMax())
.endSpec()
.build();
connectors.add(connector);
}
}
}
return connectors;
}
/* test */ Map<String, Object> prepareMirrorMaker2ConnectorConfig(KafkaMirrorMaker2MirrorSpec mirror, KafkaMirrorMaker2ConnectorSpec connector, KafkaMirrorMaker2ClusterSpec sourceCluster, KafkaMirrorMaker2ClusterSpec targetCluster) {
Map<String, Object> config = new HashMap<>(connector.getConfig());
// Source and target cluster configurations
addClusterToMirrorMaker2ConnectorConfig(config, targetCluster, TARGET_CLUSTER_PREFIX);
addClusterToMirrorMaker2ConnectorConfig(config, sourceCluster, SOURCE_CLUSTER_PREFIX);
// Topics pattern
if (mirror.getTopicsPattern() != null) {
config.put("topics", mirror.getTopicsPattern());
}
// Topics exclusion pattern
String topicsExcludePattern = mirror.getTopicsExcludePattern();
@SuppressWarnings("deprecation") // getTopicsBlacklistPattern() is deprecated
String topicsBlacklistPattern = mirror.getTopicsBlacklistPattern();
if (topicsExcludePattern != null && topicsBlacklistPattern != null) {
LOGGER.warnCr(reconciliation, "Both topicsExcludePattern and topicsBlacklistPattern mirror properties are present, ignoring topicsBlacklistPattern as it is deprecated");
}
String topicsExclude = topicsExcludePattern != null ? topicsExcludePattern : topicsBlacklistPattern;
if (topicsExclude != null) {
config.put("topics.exclude", topicsExclude);
}
// Groups pattern
if (mirror.getGroupsPattern() != null) {
config.put("groups", mirror.getGroupsPattern());
}
// Groups exclusion pattern
String groupsExcludePattern = mirror.getGroupsExcludePattern();
@SuppressWarnings("deprecation") // getGroupsBlacklistPattern() is deprecated
String groupsBlacklistPattern = mirror.getGroupsBlacklistPattern();
if (groupsExcludePattern != null && groupsBlacklistPattern != null) {
LOGGER.warnCr(reconciliation, "Both groupsExcludePattern and groupsBlacklistPattern mirror properties are present, ignoring groupsBlacklistPattern as it is deprecated");
}
String groupsExclude = groupsExcludePattern != null ? groupsExcludePattern : groupsBlacklistPattern;
if (groupsExclude != null) {
config.put("groups.exclude", groupsExclude);
}
// Tracing
if (tracing != null) {
@SuppressWarnings("deprecation") // JaegerTracing is deprecated
String jaegerType = JaegerTracing.TYPE_JAEGER;
if (jaegerType.equals(tracing.getType())) {
LOGGER.warnCr(reconciliation, "Tracing type \"{}\" is not supported anymore and will be ignored", jaegerType);
} else if (OpenTelemetryTracing.TYPE_OPENTELEMETRY.equals(tracing.getType())) {
config.put("consumer.interceptor.classes", OpenTelemetryTracing.CONSUMER_INTERCEPTOR_CLASS_NAME);
config.put("producer.interceptor.classes", OpenTelemetryTracing.PRODUCER_INTERCEPTOR_CLASS_NAME);
}
}
// Rack awareness (client.rack has to be configured in the connector because the consumer is created by the connector)
if (rackAwarenessEnabled) {
String clientRackKey = "consumer.client.rack";
config.put(clientRackKey, "${file:" + CONNECT_CONFIG_FILE + ":" + clientRackKey + "}");
}
return config;
}
/* test */ static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) {
config.put(configPrefix + "alias", cluster.getAlias());
config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
String securityProtocol = addTLSConfigToMirrorMaker2ConnectorConfig(config, cluster, configPrefix);
if (cluster.getAuthentication() != null) {
if (cluster.getAuthentication() instanceof KafkaClientAuthenticationTls) {
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12");
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, STORE_LOCATION_ROOT + cluster.getAlias() + KEYSTORE_SUFFIX);
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "${file:" + CONNECTORS_CONFIG_FILE + ":" + SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG + "}");
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationPlain plainAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, "PLAIN");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.plain.PlainLoginModule",
Map.of("username", plainAuthentication.getUsername(),
"password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".sasl.password}")));
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationScram scramAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, scramAuthentication instanceof KafkaClientAuthenticationScramSha256 ? "SCRAM-SHA-256" : "SCRAM-SHA-512");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.scram.ScramLoginModule",
Map.of("username", scramAuthentication.getUsername(),
"password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".sasl.password}")));
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationOAuth oauthAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, "OAUTHBEARER");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
oauthJaasConfig(cluster, oauthAuthentication));
config.put(configPrefix + SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS, "io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler");
}
}
// Security protocol
config.put(configPrefix + AdminClientConfig.SECURITY_PROTOCOL_CONFIG, securityProtocol);
config.putAll(cluster.getConfig().entrySet().stream()
.collect(Collectors.toMap(entry -> configPrefix + entry.getKey(), Map.Entry::getValue)));
config.putAll(cluster.getAdditionalProperties());
}
private static String oauthJaasConfig(KafkaMirrorMaker2ClusterSpec cluster, KafkaClientAuthenticationOAuth oauth) {
Map<String, String> jaasOptions = cluster.getAuthentication() instanceof KafkaClientAuthenticationOAuth ? AuthenticationUtils.oauthJaasOptions((KafkaClientAuthenticationOAuth) cluster.getAuthentication()) : new LinkedHashMap<>();
if (oauth.getClientSecret() != null) {
jaasOptions.put("oauth.client.secret", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.client.secret}");
}
if (oauth.getAccessToken() != null) {
jaasOptions.put("oauth.access.token", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.access.token}");
}
if (oauth.getRefreshToken() != null) {
jaasOptions.put("oauth.refresh.token", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.refresh.token}");
}
if (oauth.getPasswordSecret() != null) {
jaasOptions.put("oauth.password.grant.password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.password.grant.password}");
}
if (oauth.getTlsTrustedCertificates() != null && !oauth.getTlsTrustedCertificates().isEmpty()) {
jaasOptions.put("oauth.ssl.truststore.location", "/tmp/kafka/clusters/" + cluster.getAlias() + "-oauth.truststore.p12");
jaasOptions.put("oauth.ssl.truststore.password", "${file:" + CONNECTORS_CONFIG_FILE + ":oauth.ssl.truststore.password}");
jaasOptions.put("oauth.ssl.truststore.type", "PKCS12");
}
return AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule", jaasOptions);
}
/**
* Adds configuration for the TLS encryption to the map if TLS is configured and returns the security protocol
* (SSL or PLAINTEXT). The returned security protocol is later modified for SASL if needed, but this is done in the
* parent method.
*
* @param config Map with the configuration
* @param cluster Cluster configuration (.spec.clusters property from the MM2 custom resource)
* @param configPrefix Prefix string for the added configuration options
*
* @return String indicating whether the security protocol should be SSL or PLAINTEXT based
*/
private static String addTLSConfigToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) {
if (cluster.getTls() != null) {
if (cluster.getTls().getTrustedCertificates() != null && !cluster.getTls().getTrustedCertificates().isEmpty()) {
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12");
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, STORE_LOCATION_ROOT + cluster.getAlias() + TRUSTSTORE_SUFFIX);
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "${file:" + CONNECTORS_CONFIG_FILE + ":" + SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG + "}");
}
return "SSL";
} else {
return "PLAINTEXT";
}
}
}
| strimzi/strimzi-kafka-operator | cluster-operator/src/main/java/io/strimzi/operator/cluster/model/KafkaMirrorMaker2Connectors.java | 5,727 | // getPause() is deprecated | line_comment | nl | /*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.model;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationOAuth;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationPlain;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationScram;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationScramSha256;
import io.strimzi.api.kafka.model.common.authentication.KafkaClientAuthenticationTls;
import io.strimzi.api.kafka.model.common.tracing.JaegerTracing;
import io.strimzi.api.kafka.model.common.tracing.OpenTelemetryTracing;
import io.strimzi.api.kafka.model.common.tracing.Tracing;
import io.strimzi.api.kafka.model.connector.KafkaConnector;
import io.strimzi.api.kafka.model.connector.KafkaConnectorBuilder;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2ClusterSpec;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2ConnectorSpec;
import io.strimzi.api.kafka.model.mirrormaker2.KafkaMirrorMaker2MirrorSpec;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.ReconciliationLogger;
import io.strimzi.operator.common.model.InvalidResourceException;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.SslConfigs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Kafka Mirror Maker 2 Connectors model
*/
public class KafkaMirrorMaker2Connectors {
private static final ReconciliationLogger LOGGER = ReconciliationLogger.create(KafkaMirrorMaker2Connectors.class.getName());
private static final String CONNECTOR_JAVA_PACKAGE = "org.apache.kafka.connect.mirror";
private static final String TARGET_CLUSTER_PREFIX = "target.cluster.";
private static final String SOURCE_CLUSTER_PREFIX = "source.cluster.";
private static final String STORE_LOCATION_ROOT = "/tmp/kafka/clusters/";
private static final String TRUSTSTORE_SUFFIX = ".truststore.p12";
private static final String KEYSTORE_SUFFIX = ".keystore.p12";
private static final String CONNECT_CONFIG_FILE = "/tmp/strimzi-connect.properties";
private static final String CONNECTORS_CONFIG_FILE = "/tmp/strimzi-mirrormaker2-connector.properties";
private static final String SOURCE_CONNECTOR_SUFFIX = ".MirrorSourceConnector";
private static final String CHECKPOINT_CONNECTOR_SUFFIX = ".MirrorCheckpointConnector";
private static final String HEARTBEAT_CONNECTOR_SUFFIX = ".MirrorHeartbeatConnector";
private static final Map<String, Function<KafkaMirrorMaker2MirrorSpec, KafkaMirrorMaker2ConnectorSpec>> CONNECTORS = Map.of(
SOURCE_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getSourceConnector,
CHECKPOINT_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getCheckpointConnector,
HEARTBEAT_CONNECTOR_SUFFIX, KafkaMirrorMaker2MirrorSpec::getHeartbeatConnector
);
private final Reconciliation reconciliation;
private final Map<String, KafkaMirrorMaker2ClusterSpec> clusters;
private final List<KafkaMirrorMaker2MirrorSpec> mirrors;
private final Tracing tracing;
private final boolean rackAwarenessEnabled;
/**
* Constructor
*
* @param reconciliation Reconciliation marker
* @param kafkaMirrorMaker2 KafkaMirrorMaker2 custom resource
*/
private KafkaMirrorMaker2Connectors(Reconciliation reconciliation, KafkaMirrorMaker2 kafkaMirrorMaker2) {
this.reconciliation = reconciliation;
this.clusters = kafkaMirrorMaker2.getSpec().getClusters().stream().collect(Collectors.toMap(KafkaMirrorMaker2ClusterSpec::getAlias, Function.identity()));
this.mirrors = kafkaMirrorMaker2.getSpec().getMirrors();
this.tracing = kafkaMirrorMaker2.getSpec().getTracing();
this.rackAwarenessEnabled = kafkaMirrorMaker2.getSpec().getRack() != null;
}
/**
* Creates and returns a Mirror Maker 2 Connectors instance
*
* @param reconciliation Reconciliation marker
* @param kafkaMirrorMaker2 KafkaMirrorMaker2 custom resource
*
* @return Newly created KafkaMirrorMaker2Connectors instance
*/
public static KafkaMirrorMaker2Connectors fromCrd(Reconciliation reconciliation, KafkaMirrorMaker2 kafkaMirrorMaker2) {
validateConnectors(kafkaMirrorMaker2);
return new KafkaMirrorMaker2Connectors(reconciliation, kafkaMirrorMaker2);
}
/* test */ static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) {
if (kafkaMirrorMaker2.getSpec() == null) {
throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource");
} else {
if (kafkaMirrorMaker2.getSpec().getClusters() == null || kafkaMirrorMaker2.getSpec().getMirrors() == null) {
throw new InvalidResourceException(".spec.clusters and .spec.mirrors sections are required in KafkaMirrorMaker2 resource");
} else {
Set<String> existingClusterAliases = kafkaMirrorMaker2.getSpec().getClusters().stream().map(KafkaMirrorMaker2ClusterSpec::getAlias).collect(Collectors.toSet());
Set<String> errorMessages = new HashSet<>();
String connectCluster = kafkaMirrorMaker2.getSpec().getConnectCluster();
for (KafkaMirrorMaker2MirrorSpec mirror : kafkaMirrorMaker2.getSpec().getMirrors()) {
if (mirror.getSourceCluster() == null) {
errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the source cluster alias");
} else if (!existingClusterAliases.contains(mirror.getSourceCluster())) {
errorMessages.add("Source cluster alias " + mirror.getSourceCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions");
}
if (mirror.getTargetCluster() == null) {
errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the target cluster alias");
} else if (!existingClusterAliases.contains(mirror.getTargetCluster())) {
errorMessages.add("Target cluster alias " + mirror.getTargetCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions");
}
if (!mirror.getTargetCluster().equals(connectCluster)) {
errorMessages.add("Connect cluster alias (currently set to " + connectCluster + ") has to be the same as the target cluster alias " + mirror.getTargetCluster());
}
}
if (!errorMessages.isEmpty()) {
throw new InvalidResourceException("KafkaMirrorMaker2 resource validation failed: " + errorMessages);
}
}
}
}
/**
* @return List with connector definitions for this Mirror Maker 2 cluster
*/
public List<KafkaConnector> generateConnectorDefinitions() {
List<KafkaConnector> connectors = new ArrayList<>();
for (KafkaMirrorMaker2MirrorSpec mirror : mirrors) {
for (Entry<String, Function<KafkaMirrorMaker2MirrorSpec, KafkaMirrorMaker2ConnectorSpec>> connectorType : CONNECTORS.entrySet()) {
// Get the connector spec from the MM2 CR definitions
KafkaMirrorMaker2ConnectorSpec mm2ConnectorSpec = connectorType.getValue().apply(mirror);
if (mm2ConnectorSpec != null) {
@SuppressWarnings("deprecation") // getPause() is<SUF>
KafkaConnector connector = new KafkaConnectorBuilder()
.withNewMetadata()
.withName(mirror.getSourceCluster() + "->" + mirror.getTargetCluster() + connectorType.getKey())
.endMetadata()
.withNewSpec()
.withClassName(CONNECTOR_JAVA_PACKAGE + connectorType.getKey())
.withConfig(prepareMirrorMaker2ConnectorConfig(mirror, mm2ConnectorSpec, clusters.get(mirror.getSourceCluster()), clusters.get(mirror.getTargetCluster())))
.withPause(mm2ConnectorSpec.getPause())
.withState(mm2ConnectorSpec.getState())
.withAutoRestart(mm2ConnectorSpec.getAutoRestart())
.withTasksMax(mm2ConnectorSpec.getTasksMax())
.endSpec()
.build();
connectors.add(connector);
}
}
}
return connectors;
}
/* test */ Map<String, Object> prepareMirrorMaker2ConnectorConfig(KafkaMirrorMaker2MirrorSpec mirror, KafkaMirrorMaker2ConnectorSpec connector, KafkaMirrorMaker2ClusterSpec sourceCluster, KafkaMirrorMaker2ClusterSpec targetCluster) {
Map<String, Object> config = new HashMap<>(connector.getConfig());
// Source and target cluster configurations
addClusterToMirrorMaker2ConnectorConfig(config, targetCluster, TARGET_CLUSTER_PREFIX);
addClusterToMirrorMaker2ConnectorConfig(config, sourceCluster, SOURCE_CLUSTER_PREFIX);
// Topics pattern
if (mirror.getTopicsPattern() != null) {
config.put("topics", mirror.getTopicsPattern());
}
// Topics exclusion pattern
String topicsExcludePattern = mirror.getTopicsExcludePattern();
@SuppressWarnings("deprecation") // getTopicsBlacklistPattern() is deprecated
String topicsBlacklistPattern = mirror.getTopicsBlacklistPattern();
if (topicsExcludePattern != null && topicsBlacklistPattern != null) {
LOGGER.warnCr(reconciliation, "Both topicsExcludePattern and topicsBlacklistPattern mirror properties are present, ignoring topicsBlacklistPattern as it is deprecated");
}
String topicsExclude = topicsExcludePattern != null ? topicsExcludePattern : topicsBlacklistPattern;
if (topicsExclude != null) {
config.put("topics.exclude", topicsExclude);
}
// Groups pattern
if (mirror.getGroupsPattern() != null) {
config.put("groups", mirror.getGroupsPattern());
}
// Groups exclusion pattern
String groupsExcludePattern = mirror.getGroupsExcludePattern();
@SuppressWarnings("deprecation") // getGroupsBlacklistPattern() is deprecated
String groupsBlacklistPattern = mirror.getGroupsBlacklistPattern();
if (groupsExcludePattern != null && groupsBlacklistPattern != null) {
LOGGER.warnCr(reconciliation, "Both groupsExcludePattern and groupsBlacklistPattern mirror properties are present, ignoring groupsBlacklistPattern as it is deprecated");
}
String groupsExclude = groupsExcludePattern != null ? groupsExcludePattern : groupsBlacklistPattern;
if (groupsExclude != null) {
config.put("groups.exclude", groupsExclude);
}
// Tracing
if (tracing != null) {
@SuppressWarnings("deprecation") // JaegerTracing is deprecated
String jaegerType = JaegerTracing.TYPE_JAEGER;
if (jaegerType.equals(tracing.getType())) {
LOGGER.warnCr(reconciliation, "Tracing type \"{}\" is not supported anymore and will be ignored", jaegerType);
} else if (OpenTelemetryTracing.TYPE_OPENTELEMETRY.equals(tracing.getType())) {
config.put("consumer.interceptor.classes", OpenTelemetryTracing.CONSUMER_INTERCEPTOR_CLASS_NAME);
config.put("producer.interceptor.classes", OpenTelemetryTracing.PRODUCER_INTERCEPTOR_CLASS_NAME);
}
}
// Rack awareness (client.rack has to be configured in the connector because the consumer is created by the connector)
if (rackAwarenessEnabled) {
String clientRackKey = "consumer.client.rack";
config.put(clientRackKey, "${file:" + CONNECT_CONFIG_FILE + ":" + clientRackKey + "}");
}
return config;
}
/* test */ static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) {
config.put(configPrefix + "alias", cluster.getAlias());
config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
String securityProtocol = addTLSConfigToMirrorMaker2ConnectorConfig(config, cluster, configPrefix);
if (cluster.getAuthentication() != null) {
if (cluster.getAuthentication() instanceof KafkaClientAuthenticationTls) {
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12");
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, STORE_LOCATION_ROOT + cluster.getAlias() + KEYSTORE_SUFFIX);
config.put(configPrefix + SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "${file:" + CONNECTORS_CONFIG_FILE + ":" + SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG + "}");
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationPlain plainAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, "PLAIN");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.plain.PlainLoginModule",
Map.of("username", plainAuthentication.getUsername(),
"password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".sasl.password}")));
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationScram scramAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, scramAuthentication instanceof KafkaClientAuthenticationScramSha256 ? "SCRAM-SHA-256" : "SCRAM-SHA-512");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.scram.ScramLoginModule",
Map.of("username", scramAuthentication.getUsername(),
"password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".sasl.password}")));
} else if (cluster.getAuthentication() instanceof KafkaClientAuthenticationOAuth oauthAuthentication) {
securityProtocol = cluster.getTls() != null ? "SASL_SSL" : "SASL_PLAINTEXT";
config.put(configPrefix + SaslConfigs.SASL_MECHANISM, "OAUTHBEARER");
config.put(configPrefix + SaslConfigs.SASL_JAAS_CONFIG,
oauthJaasConfig(cluster, oauthAuthentication));
config.put(configPrefix + SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS, "io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler");
}
}
// Security protocol
config.put(configPrefix + AdminClientConfig.SECURITY_PROTOCOL_CONFIG, securityProtocol);
config.putAll(cluster.getConfig().entrySet().stream()
.collect(Collectors.toMap(entry -> configPrefix + entry.getKey(), Map.Entry::getValue)));
config.putAll(cluster.getAdditionalProperties());
}
private static String oauthJaasConfig(KafkaMirrorMaker2ClusterSpec cluster, KafkaClientAuthenticationOAuth oauth) {
Map<String, String> jaasOptions = cluster.getAuthentication() instanceof KafkaClientAuthenticationOAuth ? AuthenticationUtils.oauthJaasOptions((KafkaClientAuthenticationOAuth) cluster.getAuthentication()) : new LinkedHashMap<>();
if (oauth.getClientSecret() != null) {
jaasOptions.put("oauth.client.secret", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.client.secret}");
}
if (oauth.getAccessToken() != null) {
jaasOptions.put("oauth.access.token", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.access.token}");
}
if (oauth.getRefreshToken() != null) {
jaasOptions.put("oauth.refresh.token", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.refresh.token}");
}
if (oauth.getPasswordSecret() != null) {
jaasOptions.put("oauth.password.grant.password", "${file:" + CONNECTORS_CONFIG_FILE + ":" + cluster.getAlias() + ".oauth.password.grant.password}");
}
if (oauth.getTlsTrustedCertificates() != null && !oauth.getTlsTrustedCertificates().isEmpty()) {
jaasOptions.put("oauth.ssl.truststore.location", "/tmp/kafka/clusters/" + cluster.getAlias() + "-oauth.truststore.p12");
jaasOptions.put("oauth.ssl.truststore.password", "${file:" + CONNECTORS_CONFIG_FILE + ":oauth.ssl.truststore.password}");
jaasOptions.put("oauth.ssl.truststore.type", "PKCS12");
}
return AuthenticationUtils.jaasConfig("org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule", jaasOptions);
}
/**
* Adds configuration for the TLS encryption to the map if TLS is configured and returns the security protocol
* (SSL or PLAINTEXT). The returned security protocol is later modified for SASL if needed, but this is done in the
* parent method.
*
* @param config Map with the configuration
* @param cluster Cluster configuration (.spec.clusters property from the MM2 custom resource)
* @param configPrefix Prefix string for the added configuration options
*
* @return String indicating whether the security protocol should be SSL or PLAINTEXT based
*/
private static String addTLSConfigToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) {
if (cluster.getTls() != null) {
if (cluster.getTls().getTrustedCertificates() != null && !cluster.getTls().getTrustedCertificates().isEmpty()) {
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12");
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, STORE_LOCATION_ROOT + cluster.getAlias() + TRUSTSTORE_SUFFIX);
config.put(configPrefix + SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "${file:" + CONNECTORS_CONFIG_FILE + ":" + SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG + "}");
}
return "SSL";
} else {
return "PLAINTEXT";
}
}
}
|
144427_8 | /* LanguageTool, a natural language style checker
* Copyright (C) 2023 Mark Baas
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.nl;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import org.languagetool.*;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.spelling.CachingWordListLoader;
import org.languagetool.tagging.nl.DutchTagger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
/**
* Accept Dutch compounds that are not accepted by the speller. This code
* is supposed to accept more words in order to extend the speller, but it's not meant
* to accept all valid compounds.
* It works on 2-part compounds only for now.
*/
public class CompoundAcceptor {
private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-");
private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-");
private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*");
private static final int MAX_WORD_SIZE = 35;
public static final CompoundAcceptor INSTANCE = new CompoundAcceptor();
protected final CachingWordListLoader wordListLoader = new CachingWordListLoader();
protected final Set<String> noS = new ObjectOpenHashSet<>(),
needsS = new ObjectOpenHashSet<>(),
geographicalDirections = new ObjectOpenHashSet<>(),
alwaysNeedsS = new ObjectOpenHashSet<>(),
alwaysNeedsHyphen = new ObjectOpenHashSet<>(),
part1Exceptions = new ObjectOpenHashSet<>(),
part2Exceptions = new ObjectOpenHashSet<>(),
acronymExceptions = new ObjectOpenHashSet<>();
private static final String COMPOUND_NO_S_FILE = "nl/compound_acceptor/no_s.txt",
COMPOUND_NEEDS_S_FILE = "nl/compound_acceptor/needs_s.txt",
COMPOUND_DIRECTIONS_FILE = "nl/compound_acceptor/directions.txt",
COMPOUND_ALWAYS_NEEDS_S_FILE = "nl/compound_acceptor/always_needs_s.txt",
COMPOUND_ALWAYS_NEEDS_HYPHEN_FILE = "nl/compound_acceptor/always_needs_hyphen.txt",
COMPOUND_PART1_EXCEPTIONS_FILE = "nl/compound_acceptor/part1_exceptions.txt",
COMPOUND_PART2_EXCEPTIONS_FILE = "nl/compound_acceptor/part2_exceptions.txt",
COMPOUND_ACRONYM_EXCEPTIONS_FILE = "nl/compound_acceptor/acronym_exceptions.txt";
// Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid".
private final Set<String> collidingVowels = ImmutableSet.of(
"aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu"
);
private static final MorfologikDutchSpellerRule speller;
static {
try {
speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final DutchTagger dutchTagger = DutchTagger.INSTANCE;
public CompoundAcceptor() {
noS.addAll(wordListLoader.loadWords(COMPOUND_NO_S_FILE));
needsS.addAll(wordListLoader.loadWords(COMPOUND_NEEDS_S_FILE));
geographicalDirections.addAll(wordListLoader.loadWords(COMPOUND_DIRECTIONS_FILE));
alwaysNeedsS.addAll(wordListLoader.loadWords(COMPOUND_ALWAYS_NEEDS_S_FILE));
alwaysNeedsHyphen.addAll(wordListLoader.loadWords(COMPOUND_ALWAYS_NEEDS_HYPHEN_FILE));
part1Exceptions.addAll(wordListLoader.loadWords(COMPOUND_PART1_EXCEPTIONS_FILE));
part2Exceptions.addAll(wordListLoader.loadWords(COMPOUND_PART2_EXCEPTIONS_FILE));
acronymExceptions.addAll(wordListLoader.loadWords(COMPOUND_ACRONYM_EXCEPTIONS_FILE));
}
boolean acceptCompound(String word) {
if (word.length() > MAX_WORD_SIZE) { // prevent long runtime
return false;
}
for (int i = 3; i < word.length() - 3; i++) {
String part1 = word.substring(0, i);
String part2 = word.substring(i);
if (!part1.equals(part2) && acceptCompound(part1, part2)) {
System.out.println(part1+part2 + " -> accepted");
return true;
}
}
return false;
}
public List<String> getParts(String word) {
if (word.length() > MAX_WORD_SIZE) { // prevent long runtime
return Collections.emptyList();
}
for (int i = 3; i < word.length() - 3; i++) {
String part1 = word.substring(0, i);
String part2 = word.substring(i);
if (!part1.equals(part2) && acceptCompound(part1, part2)) {
return Arrays.asList(part1, part2);
}
}
return Collections.emptyList();
}
boolean acceptCompound(String part1, String part2) {
try {
String part1lc = part1.toLowerCase();
// reject if it's in the exceptions list or if a wildcard is the entirety of part1
if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !alwaysNeedsS.contains(part1) && !noS.contains(part1) && !part1.contains("-")) {
for (String suffix : alwaysNeedsS) {
if (part1lc.endsWith(suffix)) {
return isNoun(part2) && isExistingWord(part1lc.substring(0, part1lc.length() - 1)) && spellingOk(part2);
}
}
return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2);
} else if (geographicalDirections.contains(part1)){
return isGeographicalCompound(part2); // directions
} else if (part1.endsWith("-")) { // abbreviations
return (acronymOk(part1) || alwaysNeedsHyphen.contains(part1lc)) && spellingOk(part2);
} else if (part2.startsWith("-")) { // vowel collision
part2 = part2.substring(1);
return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2);
} else {
return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && !hasCollidingVowels(part1, part2);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private boolean isNoun(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> {
assert k.getPOSTag() != null;
return k.getPOSTag().startsWith("ZNW") && !part2Exceptions.contains(word);
});
}
private boolean isExistingWord(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> k.getPOSTag() != null);
}
private boolean isGeographicalCompound(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> {
assert k.getPOSTag() != null;
return k.getPOSTag().startsWith("ENM:LOC");
});
}
private boolean hasCollidingVowels(String part1, String part2) {
char char1 = part1.charAt(part1.length() - 1);
char char2 = part2.charAt(0);
String vowels = String.valueOf(char1) + char2;
return collidingVowels.contains(vowels.toLowerCase());
}
private boolean acronymOk(String nonCompound) {
// for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten
if ( acronymPattern.matcher(nonCompound).matches() ){
return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1)));
} else if ( specialAcronymPattern.matcher(nonCompound).matches() ) {
// special case acronyms that are accepted only with specific casing
return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1));
} else {
return false;
}
}
private boolean spellingOk(String nonCompound) throws IOException {
if (!normalCasePattern.matcher(nonCompound).matches()) {
return false; // e.g. kinderenHet -> split as kinder,enHet
}
AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] {
new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma"))
});
RuleMatch[] matches = speller.match(as);
return matches.length == 0;
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>");
System.exit(1);
}
CompoundAcceptor acceptor = new CompoundAcceptor();
List<String> words = Files.readAllLines(Paths.get(args[0]));
for (String word : words) {
boolean accepted = acceptor.acceptCompound(word);
System.out.println(accepted + " " + word);
}
}
}
| strn/languagetool-sr | languagetool-language-modules/nl/src/main/java/org/languagetool/rules/nl/CompoundAcceptor.java | 3,158 | // e.g. kinderenHet -> split as kinder,enHet | line_comment | nl | /* LanguageTool, a natural language style checker
* Copyright (C) 2023 Mark Baas
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.nl;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import org.languagetool.*;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.spelling.CachingWordListLoader;
import org.languagetool.tagging.nl.DutchTagger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
/**
* Accept Dutch compounds that are not accepted by the speller. This code
* is supposed to accept more words in order to extend the speller, but it's not meant
* to accept all valid compounds.
* It works on 2-part compounds only for now.
*/
public class CompoundAcceptor {
private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-");
private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-");
private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*");
private static final int MAX_WORD_SIZE = 35;
public static final CompoundAcceptor INSTANCE = new CompoundAcceptor();
protected final CachingWordListLoader wordListLoader = new CachingWordListLoader();
protected final Set<String> noS = new ObjectOpenHashSet<>(),
needsS = new ObjectOpenHashSet<>(),
geographicalDirections = new ObjectOpenHashSet<>(),
alwaysNeedsS = new ObjectOpenHashSet<>(),
alwaysNeedsHyphen = new ObjectOpenHashSet<>(),
part1Exceptions = new ObjectOpenHashSet<>(),
part2Exceptions = new ObjectOpenHashSet<>(),
acronymExceptions = new ObjectOpenHashSet<>();
private static final String COMPOUND_NO_S_FILE = "nl/compound_acceptor/no_s.txt",
COMPOUND_NEEDS_S_FILE = "nl/compound_acceptor/needs_s.txt",
COMPOUND_DIRECTIONS_FILE = "nl/compound_acceptor/directions.txt",
COMPOUND_ALWAYS_NEEDS_S_FILE = "nl/compound_acceptor/always_needs_s.txt",
COMPOUND_ALWAYS_NEEDS_HYPHEN_FILE = "nl/compound_acceptor/always_needs_hyphen.txt",
COMPOUND_PART1_EXCEPTIONS_FILE = "nl/compound_acceptor/part1_exceptions.txt",
COMPOUND_PART2_EXCEPTIONS_FILE = "nl/compound_acceptor/part2_exceptions.txt",
COMPOUND_ACRONYM_EXCEPTIONS_FILE = "nl/compound_acceptor/acronym_exceptions.txt";
// Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid".
private final Set<String> collidingVowels = ImmutableSet.of(
"aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu"
);
private static final MorfologikDutchSpellerRule speller;
static {
try {
speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final DutchTagger dutchTagger = DutchTagger.INSTANCE;
public CompoundAcceptor() {
noS.addAll(wordListLoader.loadWords(COMPOUND_NO_S_FILE));
needsS.addAll(wordListLoader.loadWords(COMPOUND_NEEDS_S_FILE));
geographicalDirections.addAll(wordListLoader.loadWords(COMPOUND_DIRECTIONS_FILE));
alwaysNeedsS.addAll(wordListLoader.loadWords(COMPOUND_ALWAYS_NEEDS_S_FILE));
alwaysNeedsHyphen.addAll(wordListLoader.loadWords(COMPOUND_ALWAYS_NEEDS_HYPHEN_FILE));
part1Exceptions.addAll(wordListLoader.loadWords(COMPOUND_PART1_EXCEPTIONS_FILE));
part2Exceptions.addAll(wordListLoader.loadWords(COMPOUND_PART2_EXCEPTIONS_FILE));
acronymExceptions.addAll(wordListLoader.loadWords(COMPOUND_ACRONYM_EXCEPTIONS_FILE));
}
boolean acceptCompound(String word) {
if (word.length() > MAX_WORD_SIZE) { // prevent long runtime
return false;
}
for (int i = 3; i < word.length() - 3; i++) {
String part1 = word.substring(0, i);
String part2 = word.substring(i);
if (!part1.equals(part2) && acceptCompound(part1, part2)) {
System.out.println(part1+part2 + " -> accepted");
return true;
}
}
return false;
}
public List<String> getParts(String word) {
if (word.length() > MAX_WORD_SIZE) { // prevent long runtime
return Collections.emptyList();
}
for (int i = 3; i < word.length() - 3; i++) {
String part1 = word.substring(0, i);
String part2 = word.substring(i);
if (!part1.equals(part2) && acceptCompound(part1, part2)) {
return Arrays.asList(part1, part2);
}
}
return Collections.emptyList();
}
boolean acceptCompound(String part1, String part2) {
try {
String part1lc = part1.toLowerCase();
// reject if it's in the exceptions list or if a wildcard is the entirety of part1
if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !alwaysNeedsS.contains(part1) && !noS.contains(part1) && !part1.contains("-")) {
for (String suffix : alwaysNeedsS) {
if (part1lc.endsWith(suffix)) {
return isNoun(part2) && isExistingWord(part1lc.substring(0, part1lc.length() - 1)) && spellingOk(part2);
}
}
return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2);
} else if (geographicalDirections.contains(part1)){
return isGeographicalCompound(part2); // directions
} else if (part1.endsWith("-")) { // abbreviations
return (acronymOk(part1) || alwaysNeedsHyphen.contains(part1lc)) && spellingOk(part2);
} else if (part2.startsWith("-")) { // vowel collision
part2 = part2.substring(1);
return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2);
} else {
return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && !hasCollidingVowels(part1, part2);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private boolean isNoun(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> {
assert k.getPOSTag() != null;
return k.getPOSTag().startsWith("ZNW") && !part2Exceptions.contains(word);
});
}
private boolean isExistingWord(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> k.getPOSTag() != null);
}
private boolean isGeographicalCompound(String word) throws IOException {
return dutchTagger.getPostags(word).stream().anyMatch(k -> {
assert k.getPOSTag() != null;
return k.getPOSTag().startsWith("ENM:LOC");
});
}
private boolean hasCollidingVowels(String part1, String part2) {
char char1 = part1.charAt(part1.length() - 1);
char char2 = part2.charAt(0);
String vowels = String.valueOf(char1) + char2;
return collidingVowels.contains(vowels.toLowerCase());
}
private boolean acronymOk(String nonCompound) {
// for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten
if ( acronymPattern.matcher(nonCompound).matches() ){
return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1)));
} else if ( specialAcronymPattern.matcher(nonCompound).matches() ) {
// special case acronyms that are accepted only with specific casing
return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1));
} else {
return false;
}
}
private boolean spellingOk(String nonCompound) throws IOException {
if (!normalCasePattern.matcher(nonCompound).matches()) {
return false; // e.g. kinderenHet<SUF>
}
AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] {
new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma"))
});
RuleMatch[] matches = speller.match(as);
return matches.length == 0;
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>");
System.exit(1);
}
CompoundAcceptor acceptor = new CompoundAcceptor();
List<String> words = Files.readAllLines(Paths.get(args[0]));
for (String word : words) {
boolean accepted = acceptor.acceptCompound(word);
System.out.println(accepted + " " + word);
}
}
}
|
51825_7 | package com.iiatimd.portfolioappv2;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.iiatimd.portfolioappv2.Entities.AccessToken;
import com.iiatimd.portfolioappv2.Entities.Project;
import com.iiatimd.portfolioappv2.Entities.ProjectCall;
import com.iiatimd.portfolioappv2.Fragments.AccountFragment;
import com.iiatimd.portfolioappv2.Fragments.HomeFragment;
import com.iiatimd.portfolioappv2.Network.ApiService;
import com.iiatimd.portfolioappv2.Network.InternetCheck;
import com.iiatimd.portfolioappv2.Network.RetrofitBuilder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FloatingActionButton fab;
private BottomNavigationView navigationView;
private static final int GALLERY_ADD_PROJECT = 2;
// private SharedPreferences userPref;
private static final String TAG = "HomeActivity";
ApiService service;
TokenManager tokenManager;
UserManager userManager;
Call<ProjectCall> callProject;
InternetCheck internetCheck;
Call<AccessToken> callLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameHomeContainer,new HomeFragment(), HomeFragment.class.getSimpleName()).commit();
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
userManager = UserManager.getInstance(getSharedPreferences("user", MODE_PRIVATE));
// Als je geen tokens meer hebt, moet je weer opnieuw inloggen
if (tokenManager.getToken() == null) {
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
// Service waarbij access token automatisch wordt meegegeven
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
init();
}
public TokenManager getToken() {
return TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
}
private void init() {
navigationView = findViewById(R.id.bottom_nav);
internetCheck = new InternetCheck(getApplicationContext());
fab = findViewById(R.id.fab);
fab.setOnClickListener(v->{
if (internetCheck.isInternetAvailable()) {
startActivity(new Intent(HomeActivity.this, AddProjectActivity.class));
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setTitle("Netwerkfout");
builder.setMessage("Projecten kunnen niet toegevoegd worden als er geen verbinding met het internet is.");
builder.setPositiveButton("OK", (dialog, i) -> {});
builder.show();
}
});
// userPref = getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE);
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
// Als je voor homepage kiest
case R.id.item_home: {
Fragment account = fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName());
if (account != null) {
// Verberg Account fragment
fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName())).commit();
// Show Home fragment
fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(HomeFragment.class.getSimpleName())).commit();
}
break;
}
// Als je voor account kiest
case R.id.item_account: {
Fragment account = fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName());
fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(HomeFragment.class.getSimpleName())).commit();
if (account!=null){
// Show account fragment
fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName())).commit();
}
else {
fragmentManager.beginTransaction().add(R.id.frameHomeContainer,new AccountFragment(),AccountFragment.class.getSimpleName()).commit();
}
break;
}
}
return true;
}
});
}
// Optie voor de user om uit te loggen
public void logout() {
callLogout = service.logout(tokenManager.getToken());
callLogout.enqueue(new Callback<AccessToken>() {
@Override
public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
Log.w(TAG, "onResponse: " + response);
if (response.isSuccessful()) {
// userPref.edit().clear().apply();
// Verwijder user en tokens uit memory
userManager.deleteUser();
tokenManager.deleteToken();
// Zet recyclerview op null, belangrijk anders ontstaat er een memory leak!
if (HomeFragment.recyclerViewHome != null) {
HomeFragment.recyclerViewHome = null;
}
// Keer terug naar LoginActivity
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
}
@Override
public void onFailure(Call<AccessToken> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Logout
if (callLogout != null) {
callLogout.cancel();
callLogout = null;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ADD_PROJECT && resultCode == RESULT_OK) {
Uri imgUri = data.getData();
Intent intent = new Intent(HomeActivity.this, AddProjectActivity.class);
intent.setData(imgUri);
startActivity(intent);
}
}
} | student-techlife/Portfolio-Android-App | app/src/main/java/com/iiatimd/portfolioappv2/HomeActivity.java | 1,920 | // Als je voor account kiest | line_comment | nl | package com.iiatimd.portfolioappv2;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.iiatimd.portfolioappv2.Entities.AccessToken;
import com.iiatimd.portfolioappv2.Entities.Project;
import com.iiatimd.portfolioappv2.Entities.ProjectCall;
import com.iiatimd.portfolioappv2.Fragments.AccountFragment;
import com.iiatimd.portfolioappv2.Fragments.HomeFragment;
import com.iiatimd.portfolioappv2.Network.ApiService;
import com.iiatimd.portfolioappv2.Network.InternetCheck;
import com.iiatimd.portfolioappv2.Network.RetrofitBuilder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FloatingActionButton fab;
private BottomNavigationView navigationView;
private static final int GALLERY_ADD_PROJECT = 2;
// private SharedPreferences userPref;
private static final String TAG = "HomeActivity";
ApiService service;
TokenManager tokenManager;
UserManager userManager;
Call<ProjectCall> callProject;
InternetCheck internetCheck;
Call<AccessToken> callLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameHomeContainer,new HomeFragment(), HomeFragment.class.getSimpleName()).commit();
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
userManager = UserManager.getInstance(getSharedPreferences("user", MODE_PRIVATE));
// Als je geen tokens meer hebt, moet je weer opnieuw inloggen
if (tokenManager.getToken() == null) {
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
// Service waarbij access token automatisch wordt meegegeven
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
init();
}
public TokenManager getToken() {
return TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
}
private void init() {
navigationView = findViewById(R.id.bottom_nav);
internetCheck = new InternetCheck(getApplicationContext());
fab = findViewById(R.id.fab);
fab.setOnClickListener(v->{
if (internetCheck.isInternetAvailable()) {
startActivity(new Intent(HomeActivity.this, AddProjectActivity.class));
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setTitle("Netwerkfout");
builder.setMessage("Projecten kunnen niet toegevoegd worden als er geen verbinding met het internet is.");
builder.setPositiveButton("OK", (dialog, i) -> {});
builder.show();
}
});
// userPref = getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE);
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
// Als je voor homepage kiest
case R.id.item_home: {
Fragment account = fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName());
if (account != null) {
// Verberg Account fragment
fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName())).commit();
// Show Home fragment
fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(HomeFragment.class.getSimpleName())).commit();
}
break;
}
// Als je<SUF>
case R.id.item_account: {
Fragment account = fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName());
fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(HomeFragment.class.getSimpleName())).commit();
if (account!=null){
// Show account fragment
fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(AccountFragment.class.getSimpleName())).commit();
}
else {
fragmentManager.beginTransaction().add(R.id.frameHomeContainer,new AccountFragment(),AccountFragment.class.getSimpleName()).commit();
}
break;
}
}
return true;
}
});
}
// Optie voor de user om uit te loggen
public void logout() {
callLogout = service.logout(tokenManager.getToken());
callLogout.enqueue(new Callback<AccessToken>() {
@Override
public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
Log.w(TAG, "onResponse: " + response);
if (response.isSuccessful()) {
// userPref.edit().clear().apply();
// Verwijder user en tokens uit memory
userManager.deleteUser();
tokenManager.deleteToken();
// Zet recyclerview op null, belangrijk anders ontstaat er een memory leak!
if (HomeFragment.recyclerViewHome != null) {
HomeFragment.recyclerViewHome = null;
}
// Keer terug naar LoginActivity
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
}
@Override
public void onFailure(Call<AccessToken> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Logout
if (callLogout != null) {
callLogout.cancel();
callLogout = null;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ADD_PROJECT && resultCode == RESULT_OK) {
Uri imgUri = data.getData();
Intent intent = new Intent(HomeActivity.this, AddProjectActivity.class);
intent.setData(imgUri);
startActivity(intent);
}
}
} |
31368_5 | package be.ugent.oomo.groep12.studgent.activity;
import java.util.ArrayList;
import android.widget.AdapterView;
import java.util.HashMap;
import java.util.Map;
import be.ugent.oomo.groep12.studgent.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import be.ugent.oomo.groep12.studgent.adapter.FriendAdapter;
import be.ugent.oomo.groep12.studgent.common.Friend;
import be.ugent.oomo.groep12.studgent.common.ICalendarEvent;
import be.ugent.oomo.groep12.studgent.data.FriendListDataSource;
import be.ugent.oomo.groep12.studgent.utilities.LoginUtility;
import be.ugent.oomo.groep12.studgent.utilities.MenuUtil;
public class FriendListActivity extends Activity implements AdapterView.OnItemClickListener, TextWatcher {
protected ICalendarEvent[] event_data;
protected FriendAdapter adapter;
protected ListView friend_list_view;
protected EditText inputSearch;
protected View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.overridePendingTransition(R.anim.animation_enter,
R.anim.animation_leave);
setContentView(R.layout.activity_friendlist);
friend_list_view = (ListView) findViewById(R.id.friends_list);
friend_list_view.setOnItemClickListener(this);
inputSearch = (EditText) findViewById(R.id.searchFriends_EditText);
inputSearch.addTextChangedListener(this);
// hide keyboard on start activity
this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// create adapter with empty list and attach custom item view
adapter = new FriendAdapter(this, R.layout.friend_list_item, new ArrayList<Friend>());
friend_list_view.setAdapter(adapter);
if (LoginUtility.isLoggedIn() == false) {
Toast.makeText(this, "Log in om vrienden volgen!", Toast.LENGTH_SHORT).show();
onBackPressed();
}else{
new AsyncFriendListViewLoader().execute(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
return MenuUtil.PrepareMenu(this, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return MenuUtil.OptionsItemSelected(this, item);
}
@Override
public void onItemClick(AdapterView<?> parent, View item, int position, long rowID) {
System.out.println("geklikt op vriend");
Intent intent = new Intent(this, UserProfileActivity.class);
intent.putExtra("user", adapter.getItem(position));
startActivity(intent);
}
private class AsyncFriendListViewLoader extends AsyncTask<FriendAdapter, Void, ArrayList<Friend>> {
private final ProgressDialog dialog = new ProgressDialog(FriendListActivity.this);
@Override
protected void onPostExecute(ArrayList<Friend> result) {
super.onPostExecute(result);
dialog.dismiss();
//adapter.setItemList(result);
adapter.clear();
for(Friend friend: sortFriends(result)){
adapter.add(friend);
}
friend_list_view.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Gebruikers ophalen...");
dialog.show();
}
@Override
protected ArrayList<Friend> doInBackground(FriendAdapter... params) {
try {
Map<Integer, Friend> friends = FriendListDataSource.getInstance().getLastItems();
return new ArrayList<Friend>(friends.values());
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
}
private class AsyncFollow extends AsyncTask<Integer, Void, Boolean> {
int friendID;
boolean follow;
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
adapter.setFollowStatus(friendID, follow);
changeImageButton(result);
adapter.notifyDataSetChanged();
}
@Override
protected Boolean doInBackground(Integer... params) {
friendID = params[0];
follow = ( params[1] == 1 );
try {
boolean result = FriendListDataSource.getInstance().follow(friendID, follow);
return result;
}
catch(Throwable t) {
t.printStackTrace();
return false;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
private ArrayList<Friend> sortFriends(ArrayList<Friend> source){
ArrayList<Friend> result = new ArrayList<Friend>();
Map<Boolean,ArrayList<Friend> > vrienden = new HashMap<Boolean,ArrayList<Friend> >();
vrienden.put(true, new ArrayList<Friend>());
vrienden.put(false, new ArrayList<Friend>());
for(Friend friend: source){
vrienden.get(friend.isFollowing()).add(friend);
}
ArrayList<Friend> volgers = vrienden.get(true);
ArrayList<Friend> nietVolgers = vrienden.get(false);
for(Friend friend: volgers){
result.add(friend);
}
for(Friend friend: nietVolgers){
result.add(friend);
}
return result;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
public void changeImageButton(boolean addfriend){
if(addfriend){
view.setContentDescription(getString(R.string.friend_description));
view.setBackgroundResource(R.drawable.check);
}
else{
view.setContentDescription(getString(R.string.no_friend_description));
view.setBackgroundResource(R.drawable.add_friend);
}
view.invalidate();
}
public void change_friend_status(View view){
this.view = view;
final int friendID = (Integer) view.getTag();
//creating alert dialog frame
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
if(view.getContentDescription().equals(getString(R.string.friend_description))){ // in de adapter moet ik nog bij de niet vrienden die toegevoegd worden de contentDescription veranderen
//alert dialog opmaken voor verwijderen van vriend
alertDialogBuilder.setTitle(getString(R.string.remove_friend_title));
alertDialogBuilder.setMessage(getString(R.string.remove_friend));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Integer[] params = new Integer[2];
params[0] = friendID;
params[1] = 0; // 1 for follow, 0 for unfollow
new AsyncFollow().execute(params);
dialog.cancel();
}
});
alertDialogBuilder.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
}
else{
//alert dialog opmaken voor toevoegen van vriend
alertDialogBuilder.setTitle(getString(R.string.add_friend_title));
alertDialogBuilder.setMessage(getString(R.string.add_friend));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Integer[] params = new Integer[2];
params[0] = friendID;
params[1] = 1; // 1 for follow, 0 for unfollow
new AsyncFollow().execute(params);
dialog.cancel();
}
});
alertDialogBuilder.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
}
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
| studgent/android | src/be/ugent/oomo/groep12/studgent/activity/FriendListActivity.java | 2,684 | //alert dialog opmaken voor verwijderen van vriend | line_comment | nl | package be.ugent.oomo.groep12.studgent.activity;
import java.util.ArrayList;
import android.widget.AdapterView;
import java.util.HashMap;
import java.util.Map;
import be.ugent.oomo.groep12.studgent.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import be.ugent.oomo.groep12.studgent.adapter.FriendAdapter;
import be.ugent.oomo.groep12.studgent.common.Friend;
import be.ugent.oomo.groep12.studgent.common.ICalendarEvent;
import be.ugent.oomo.groep12.studgent.data.FriendListDataSource;
import be.ugent.oomo.groep12.studgent.utilities.LoginUtility;
import be.ugent.oomo.groep12.studgent.utilities.MenuUtil;
public class FriendListActivity extends Activity implements AdapterView.OnItemClickListener, TextWatcher {
protected ICalendarEvent[] event_data;
protected FriendAdapter adapter;
protected ListView friend_list_view;
protected EditText inputSearch;
protected View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.overridePendingTransition(R.anim.animation_enter,
R.anim.animation_leave);
setContentView(R.layout.activity_friendlist);
friend_list_view = (ListView) findViewById(R.id.friends_list);
friend_list_view.setOnItemClickListener(this);
inputSearch = (EditText) findViewById(R.id.searchFriends_EditText);
inputSearch.addTextChangedListener(this);
// hide keyboard on start activity
this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// create adapter with empty list and attach custom item view
adapter = new FriendAdapter(this, R.layout.friend_list_item, new ArrayList<Friend>());
friend_list_view.setAdapter(adapter);
if (LoginUtility.isLoggedIn() == false) {
Toast.makeText(this, "Log in om vrienden volgen!", Toast.LENGTH_SHORT).show();
onBackPressed();
}else{
new AsyncFriendListViewLoader().execute(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
return MenuUtil.PrepareMenu(this, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return MenuUtil.OptionsItemSelected(this, item);
}
@Override
public void onItemClick(AdapterView<?> parent, View item, int position, long rowID) {
System.out.println("geklikt op vriend");
Intent intent = new Intent(this, UserProfileActivity.class);
intent.putExtra("user", adapter.getItem(position));
startActivity(intent);
}
private class AsyncFriendListViewLoader extends AsyncTask<FriendAdapter, Void, ArrayList<Friend>> {
private final ProgressDialog dialog = new ProgressDialog(FriendListActivity.this);
@Override
protected void onPostExecute(ArrayList<Friend> result) {
super.onPostExecute(result);
dialog.dismiss();
//adapter.setItemList(result);
adapter.clear();
for(Friend friend: sortFriends(result)){
adapter.add(friend);
}
friend_list_view.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Gebruikers ophalen...");
dialog.show();
}
@Override
protected ArrayList<Friend> doInBackground(FriendAdapter... params) {
try {
Map<Integer, Friend> friends = FriendListDataSource.getInstance().getLastItems();
return new ArrayList<Friend>(friends.values());
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
}
private class AsyncFollow extends AsyncTask<Integer, Void, Boolean> {
int friendID;
boolean follow;
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
adapter.setFollowStatus(friendID, follow);
changeImageButton(result);
adapter.notifyDataSetChanged();
}
@Override
protected Boolean doInBackground(Integer... params) {
friendID = params[0];
follow = ( params[1] == 1 );
try {
boolean result = FriendListDataSource.getInstance().follow(friendID, follow);
return result;
}
catch(Throwable t) {
t.printStackTrace();
return false;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
private ArrayList<Friend> sortFriends(ArrayList<Friend> source){
ArrayList<Friend> result = new ArrayList<Friend>();
Map<Boolean,ArrayList<Friend> > vrienden = new HashMap<Boolean,ArrayList<Friend> >();
vrienden.put(true, new ArrayList<Friend>());
vrienden.put(false, new ArrayList<Friend>());
for(Friend friend: source){
vrienden.get(friend.isFollowing()).add(friend);
}
ArrayList<Friend> volgers = vrienden.get(true);
ArrayList<Friend> nietVolgers = vrienden.get(false);
for(Friend friend: volgers){
result.add(friend);
}
for(Friend friend: nietVolgers){
result.add(friend);
}
return result;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
public void changeImageButton(boolean addfriend){
if(addfriend){
view.setContentDescription(getString(R.string.friend_description));
view.setBackgroundResource(R.drawable.check);
}
else{
view.setContentDescription(getString(R.string.no_friend_description));
view.setBackgroundResource(R.drawable.add_friend);
}
view.invalidate();
}
public void change_friend_status(View view){
this.view = view;
final int friendID = (Integer) view.getTag();
//creating alert dialog frame
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
if(view.getContentDescription().equals(getString(R.string.friend_description))){ // in de adapter moet ik nog bij de niet vrienden die toegevoegd worden de contentDescription veranderen
//alert dialog<SUF>
alertDialogBuilder.setTitle(getString(R.string.remove_friend_title));
alertDialogBuilder.setMessage(getString(R.string.remove_friend));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Integer[] params = new Integer[2];
params[0] = friendID;
params[1] = 0; // 1 for follow, 0 for unfollow
new AsyncFollow().execute(params);
dialog.cancel();
}
});
alertDialogBuilder.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
}
else{
//alert dialog opmaken voor toevoegen van vriend
alertDialogBuilder.setTitle(getString(R.string.add_friend_title));
alertDialogBuilder.setMessage(getString(R.string.add_friend));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Integer[] params = new Integer[2];
params[0] = friendID;
params[1] = 1; // 1 for follow, 0 for unfollow
new AsyncFollow().execute(params);
dialog.cancel();
}
});
alertDialogBuilder.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
}
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
|
170492_3 | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.synthesis.nl;
import org.junit.Test;
import org.languagetool.AnalyzedToken;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class DutchSynthesizerTest {
@Test
public final void testSynthesizeStringString() throws IOException {
DutchSynthesizer synth = new DutchSynthesizer();
assertEquals(synth.synthesize(dummyToken("blablabla"),
"blablabla").length, 0);
assertEquals("[zwommen]", Arrays.toString(synth.synthesize(dummyToken("zwemmen"), "WKW:VLT:INF")));
//assertEquals("[Afro-Surinamers]", Arrays.toString(synth.synthesize(dummyToken("Afro-Surinamer"), "ZNW:MRV:DE_")));
assertEquals("[hebt, heeft]", Arrays.toString(synth.synthesize(dummyToken("hebben"), "WKW:TGW:3EP", true)));
//with regular expressions
assertEquals("[doorgeseind]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW:VTD:ONV", true)));
//assertEquals("[doorseine, doorseinenden, doorseinend, doorseinende, doorsein, doorseint, doorseinen, doorseinde, doorseinden, doorgeseind, doorgeseinde]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW.*", true)));
}
private AnalyzedToken dummyToken(String tokenStr) {
return new AnalyzedToken(tokenStr, tokenStr, tokenStr);
}
}
| stweil/languagetool | languagetool-language-modules/nl/src/test/java/org/languagetool/synthesis/nl/DutchSynthesizerTest.java | 699 | //assertEquals("[doorseine, doorseinenden, doorseinend, doorseinende, doorsein, doorseint, doorseinen, doorseinde, doorseinden, doorgeseind, doorgeseinde]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW.*", true))); | line_comment | nl | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.synthesis.nl;
import org.junit.Test;
import org.languagetool.AnalyzedToken;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class DutchSynthesizerTest {
@Test
public final void testSynthesizeStringString() throws IOException {
DutchSynthesizer synth = new DutchSynthesizer();
assertEquals(synth.synthesize(dummyToken("blablabla"),
"blablabla").length, 0);
assertEquals("[zwommen]", Arrays.toString(synth.synthesize(dummyToken("zwemmen"), "WKW:VLT:INF")));
//assertEquals("[Afro-Surinamers]", Arrays.toString(synth.synthesize(dummyToken("Afro-Surinamer"), "ZNW:MRV:DE_")));
assertEquals("[hebt, heeft]", Arrays.toString(synth.synthesize(dummyToken("hebben"), "WKW:TGW:3EP", true)));
//with regular expressions
assertEquals("[doorgeseind]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW:VTD:ONV", true)));
//assertEquals("[doorseine, doorseinenden,<SUF>
}
private AnalyzedToken dummyToken(String tokenStr) {
return new AnalyzedToken(tokenStr, tokenStr, tokenStr);
}
}
|
722_12 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, 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 warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.jdownloader.downloader.hls.HLSDownloader;
import org.jdownloader.plugins.components.hls.HlsContainer;
/*
* vrt.be network
* old content handling --> var vars12345 = Array();
*/
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://cobradecrypted\\.be/\\d+" })
public class CobraBe extends PluginForHost {
public CobraBe(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://cobra.canvas.be/";
}
// JSARRAY removed after rev 20337
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getStringProperty("mainlink", null));
// Link offline
if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || !br.containsHTML("class=\"media flashPlayer bigMediaItem\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String ext = ".mp4";
downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "") + ext);
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
final String hlsserver = br.getRegex("data-video-iphone-server=\"(https?://[^<>\"]*?)\"").getMatch(0);
final String hlsfile = br.getRegex("data-video-iphone-path=\"(mp4:[^<>\"]*?\\.m3u8)\"").getMatch(0);
if (hlsserver == null || hlsfile == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String hlsmanifest = hlsserver + "/" + hlsfile;
br.getPage(hlsmanifest);
final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br));
if (hlsbest == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String url_hls = hlsbest.getDownloadurl();
checkFFmpeg(downloadLink, "Download a HLS Stream");
dl = new HLSDownloader(downloadLink, br, url_hls);
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/CobraBe.java | 1,247 | /*
* vrt.be network
* old content handling --> var vars12345 = Array();
*/ | block_comment | nl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, 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 warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.jdownloader.downloader.hls.HLSDownloader;
import org.jdownloader.plugins.components.hls.HlsContainer;
/*
* vrt.be network
<SUF>*/
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://cobradecrypted\\.be/\\d+" })
public class CobraBe extends PluginForHost {
public CobraBe(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://cobra.canvas.be/";
}
// JSARRAY removed after rev 20337
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getStringProperty("mainlink", null));
// Link offline
if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || !br.containsHTML("class=\"media flashPlayer bigMediaItem\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String ext = ".mp4";
downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "") + ext);
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
final String hlsserver = br.getRegex("data-video-iphone-server=\"(https?://[^<>\"]*?)\"").getMatch(0);
final String hlsfile = br.getRegex("data-video-iphone-path=\"(mp4:[^<>\"]*?\\.m3u8)\"").getMatch(0);
if (hlsserver == null || hlsfile == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String hlsmanifest = hlsserver + "/" + hlsfile;
br.getPage(hlsmanifest);
final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br));
if (hlsbest == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String url_hls = hlsbest.getDownloadurl();
checkFFmpeg(downloadLink, "Download a HLS Stream");
dl = new HLSDownloader(downloadLink, br, url_hls);
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} |
207029_20 | /*******************************************************************************
* Copyright (c) 2011 - 2012 Adrian Vielsack, Christof Urbaczek, Florian Rosenthal, Michael Hoff, Moritz Lüdecke, Philip Flohr.
*
* This file is part of Sudowars.
*
* Sudowars is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sudowars 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sudowars. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Diese Datei ist Teil von Sudowars.
*
* Sudowars ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sudowars wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
* Contributors:
* initial API and implementation:
* Adrian Vielsack
* Christof Urbaczek
* Florian Rosenthal
* Michael Hoff
* Moritz Lüdecke
* Philip Flohr
******************************************************************************/
package org.sudowars.Model.Solver;
import java.util.LinkedList;
import org.sudowars.DebugHelper;
import org.sudowars.Model.Sudoku.Field.Cell;
import org.sudowars.Model.Sudoku.Field.DataCell;
import org.sudowars.Model.Sudoku.Field.DataCellBuilder;
import org.sudowars.Model.Sudoku.Field.Field;
import org.sudowars.Model.Sudoku.Field.FieldBuilder;
/**
* This class defines the functionality to solve the next cell of a {@link Field}. It uses logical
* combinations so it try to solve the next cell like a human would do.
*/
public class HumanSolver extends StrategyExecutor implements ConsecutiveSolver {
private static final long serialVersionUID = -5626584974040288389L;
/**
* Initialises the used strategies and adds them to the list by there priority.
*/
@Override
protected void createStrategies() {
this.solveStrategies = new LinkedList<SolverStrategy>();
this.solveStrategies.add(new NakedSingleStrategy());
this.solveStrategies.add(new HiddenSingleStrategy());
this.solveStrategies.add(new LockedCandidateStrategy());
this.solveStrategies.add(new NakedNCliqueStrategy());
this.solveStrategies.add(new HiddenNCliqueStrategy());
}
/**
* Saves the solution in the cell
* @param currentState the current solution state
* @param solvedCell the solved cell
* @param solution the solution of the cell
* @return <code>true</code> if the cell was saved, <code>false</code> otherwise
*/
@Override
protected boolean saveCell(SolverState currentState, int solvedCellIndex, int solution){
//the field does not allow setValue, the function return true, so the executor
//can go on and break after this hit
return true;
}
/**
* Returns the {@link SolveStep} to solve the next {@link Cell}.
* @param currentState The current field and notes of the solver
* @return {@link SolveStep} to solve the next {@link Cell}
*/
public HumanSolveStep getCellToSolveNext(SolverState currentState) throws IllegalArgumentException {
if (currentState == null) {
throw new IllegalArgumentException("given SolverState cannot be null.");
}
//clear used strategies to save all strategies necessary to solve the next cells
//from the current state
this.usedStrategies.clear();
//solve the next cell
StrategyExecutor.ExecuteResult result = this.executeStrategies(currentState, true);
//checks if calling of the strategies found a cell
HumanSolveStep humanSolveStep = null;
SolveStep solveStep = currentState.getLastSolveStep();
if (result == StrategyExecutor.ExecuteResult.UNIQUESOLUTION && solveStep.hasSolvedCell()) {
//check if the solver return a cell without a specific solution. That happens
//if the solver needs to use backtracking to solve the cell but can not write
//on the current field to save the calculated values.
if (solveStep.getSolution() == 0) {
//use backtracker to identify the solution of the cell
BacktrackingSolver solver = new BacktrackingSolver();
//build field of data cells out of the given field
FieldBuilder<DataCell> fb = new FieldBuilder<DataCell>();
Field<DataCell> solverField = fb.build(currentState.getField().getStructure(), new DataCellBuilder());
for (Cell cell : currentState.getField().getCells()) {
solverField.getCell(cell.getIndex()).setInitial(cell.isInitial());
solverField.getCell(cell.getIndex()).setValue(cell.getValue());
}
//iterate through the candidates and try to solve the field after setting the value of the cell
for (Integer candidate : currentState.getNoteManager().getNotes(solveStep.getSolvedCell())) {
//set candidate as cell value
solverField.getCell(solveStep.getSolvedCell().getIndex()).setValue(candidate);
//try to solve the field, as it is unique solvable the candidate is the
//searched solution if the field can be solved
if (solver.solve(solverField, currentState.getDependencyManager()) != null) {
solveStep = new SolveStep(solveStep.getSolvedCell(), candidate, false);
this.usedStrategies.clear();
break;
}
}
}
//generate HumanSolveStep
humanSolveStep = new HumanSolveStep(
solveStep.getSolvedCell(),
solveStep.getSolution(),
solveStep.hasChangedNotes(),
this.getUsedStrategies());
} else {
DebugHelper.log(DebugHelper.PackageName.Solver, "executeStrategies() results no unique solution or no solved cell: " + result);
}
return humanSolveStep;
}
}
| sudowars/sudowars | Sudowars/src/org/sudowars/Model/Solver/HumanSolver.java | 1,915 | //generate HumanSolveStep | line_comment | nl | /*******************************************************************************
* Copyright (c) 2011 - 2012 Adrian Vielsack, Christof Urbaczek, Florian Rosenthal, Michael Hoff, Moritz Lüdecke, Philip Flohr.
*
* This file is part of Sudowars.
*
* Sudowars is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sudowars 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sudowars. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Diese Datei ist Teil von Sudowars.
*
* Sudowars ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sudowars wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
* Contributors:
* initial API and implementation:
* Adrian Vielsack
* Christof Urbaczek
* Florian Rosenthal
* Michael Hoff
* Moritz Lüdecke
* Philip Flohr
******************************************************************************/
package org.sudowars.Model.Solver;
import java.util.LinkedList;
import org.sudowars.DebugHelper;
import org.sudowars.Model.Sudoku.Field.Cell;
import org.sudowars.Model.Sudoku.Field.DataCell;
import org.sudowars.Model.Sudoku.Field.DataCellBuilder;
import org.sudowars.Model.Sudoku.Field.Field;
import org.sudowars.Model.Sudoku.Field.FieldBuilder;
/**
* This class defines the functionality to solve the next cell of a {@link Field}. It uses logical
* combinations so it try to solve the next cell like a human would do.
*/
public class HumanSolver extends StrategyExecutor implements ConsecutiveSolver {
private static final long serialVersionUID = -5626584974040288389L;
/**
* Initialises the used strategies and adds them to the list by there priority.
*/
@Override
protected void createStrategies() {
this.solveStrategies = new LinkedList<SolverStrategy>();
this.solveStrategies.add(new NakedSingleStrategy());
this.solveStrategies.add(new HiddenSingleStrategy());
this.solveStrategies.add(new LockedCandidateStrategy());
this.solveStrategies.add(new NakedNCliqueStrategy());
this.solveStrategies.add(new HiddenNCliqueStrategy());
}
/**
* Saves the solution in the cell
* @param currentState the current solution state
* @param solvedCell the solved cell
* @param solution the solution of the cell
* @return <code>true</code> if the cell was saved, <code>false</code> otherwise
*/
@Override
protected boolean saveCell(SolverState currentState, int solvedCellIndex, int solution){
//the field does not allow setValue, the function return true, so the executor
//can go on and break after this hit
return true;
}
/**
* Returns the {@link SolveStep} to solve the next {@link Cell}.
* @param currentState The current field and notes of the solver
* @return {@link SolveStep} to solve the next {@link Cell}
*/
public HumanSolveStep getCellToSolveNext(SolverState currentState) throws IllegalArgumentException {
if (currentState == null) {
throw new IllegalArgumentException("given SolverState cannot be null.");
}
//clear used strategies to save all strategies necessary to solve the next cells
//from the current state
this.usedStrategies.clear();
//solve the next cell
StrategyExecutor.ExecuteResult result = this.executeStrategies(currentState, true);
//checks if calling of the strategies found a cell
HumanSolveStep humanSolveStep = null;
SolveStep solveStep = currentState.getLastSolveStep();
if (result == StrategyExecutor.ExecuteResult.UNIQUESOLUTION && solveStep.hasSolvedCell()) {
//check if the solver return a cell without a specific solution. That happens
//if the solver needs to use backtracking to solve the cell but can not write
//on the current field to save the calculated values.
if (solveStep.getSolution() == 0) {
//use backtracker to identify the solution of the cell
BacktrackingSolver solver = new BacktrackingSolver();
//build field of data cells out of the given field
FieldBuilder<DataCell> fb = new FieldBuilder<DataCell>();
Field<DataCell> solverField = fb.build(currentState.getField().getStructure(), new DataCellBuilder());
for (Cell cell : currentState.getField().getCells()) {
solverField.getCell(cell.getIndex()).setInitial(cell.isInitial());
solverField.getCell(cell.getIndex()).setValue(cell.getValue());
}
//iterate through the candidates and try to solve the field after setting the value of the cell
for (Integer candidate : currentState.getNoteManager().getNotes(solveStep.getSolvedCell())) {
//set candidate as cell value
solverField.getCell(solveStep.getSolvedCell().getIndex()).setValue(candidate);
//try to solve the field, as it is unique solvable the candidate is the
//searched solution if the field can be solved
if (solver.solve(solverField, currentState.getDependencyManager()) != null) {
solveStep = new SolveStep(solveStep.getSolvedCell(), candidate, false);
this.usedStrategies.clear();
break;
}
}
}
//generate HumanSolveStep<SUF>
humanSolveStep = new HumanSolveStep(
solveStep.getSolvedCell(),
solveStep.getSolution(),
solveStep.hasChangedNotes(),
this.getUsedStrategies());
} else {
DebugHelper.log(DebugHelper.PackageName.Solver, "executeStrategies() results no unique solution or no solved cell: " + result);
}
return humanSolveStep;
}
}
|
156259_4 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project 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:
*
* 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 io.netty.channel;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.MacAddressUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import static io.netty.util.internal.MacAddressUtil.defaultMachineId;
import static io.netty.util.internal.MacAddressUtil.parseMAC;
import static io.netty.util.internal.PlatformDependent.BIG_ENDIAN_NATIVE_ORDER;
/**
* The default {@link ChannelId} implementation.
*/
public final class DefaultChannelId implements ChannelId {
private static final long serialVersionUID = 3884076183504074063L;
private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class);
private static final byte[] MACHINE_ID;
private static final int PROCESS_ID_LEN = 4;
private static final int PROCESS_ID;
private static final int SEQUENCE_LEN = 4;
private static final int TIMESTAMP_LEN = 8;
private static final int RANDOM_LEN = 4;
private static final AtomicInteger nextSequence = new AtomicInteger();
/**
* Returns a new {@link DefaultChannelId} instance.
*/
public static DefaultChannelId newInstance() {
return new DefaultChannelId(MACHINE_ID,
PROCESS_ID,
nextSequence.getAndIncrement(),
Long.reverse(System.nanoTime()) ^ System.currentTimeMillis(),
PlatformDependent.threadLocalRandom().nextInt());
}
static {
int processId = -1;
String customProcessId = SystemPropertyUtil.get("io.netty.processId");
if (customProcessId != null) {
try {
processId = Integer.parseInt(customProcessId);
} catch (NumberFormatException e) {
// Malformed input.
}
if (processId < 0) {
processId = -1;
logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId);
} else if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.processId: {} (user-set)", processId);
}
}
if (processId < 0) {
processId = defaultProcessId();
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.processId: {} (auto-detected)", processId);
}
}
PROCESS_ID = processId;
byte[] machineId = null;
String customMachineId = SystemPropertyUtil.get("io.netty.machineId");
if (customMachineId != null) {
try {
machineId = parseMAC(customMachineId);
} catch (Exception e) {
logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId, e);
}
if (machineId != null) {
logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId);
}
}
if (machineId == null) {
machineId = defaultMachineId();
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.machineId: {} (auto-detected)", MacAddressUtil.formatAddress(machineId));
}
}
MACHINE_ID = machineId;
}
static int processHandlePid(ClassLoader loader) {
// pid is positive on unix, non{-1,0} on windows
int nilValue = -1;
if (PlatformDependent.javaVersion() >= 9) {
Long pid;
try {
Class<?> processHandleImplType = Class.forName("java.lang.ProcessHandle", true, loader);
Method processHandleCurrent = processHandleImplType.getMethod("current");
Object processHandleInstance = processHandleCurrent.invoke(null);
Method processHandlePid = processHandleImplType.getMethod("pid");
pid = (Long) processHandlePid.invoke(processHandleInstance);
} catch (Exception e) {
logger.debug("Could not invoke ProcessHandle.current().pid();", e);
return nilValue;
}
if (pid > Integer.MAX_VALUE || pid < Integer.MIN_VALUE) {
throw new IllegalStateException("Current process ID exceeds int range: " + pid);
}
return pid.intValue();
}
return nilValue;
}
static int jmxPid(ClassLoader loader) {
String value;
try {
// Invoke java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
Class<?> mgmtFactoryType = Class.forName("java.lang.management.ManagementFactory", true, loader);
Class<?> runtimeMxBeanType = Class.forName("java.lang.management.RuntimeMXBean", true, loader);
Method getRuntimeMXBean = mgmtFactoryType.getMethod("getRuntimeMXBean", EmptyArrays.EMPTY_CLASSES);
Object bean = getRuntimeMXBean.invoke(null, EmptyArrays.EMPTY_OBJECTS);
Method getName = runtimeMxBeanType.getMethod("getName", EmptyArrays.EMPTY_CLASSES);
value = (String) getName.invoke(bean, EmptyArrays.EMPTY_OBJECTS);
} catch (Throwable t) {
logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(); Android?", t);
try {
// Invoke android.os.Process.myPid()
Class<?> processType = Class.forName("android.os.Process", true, loader);
Method myPid = processType.getMethod("myPid", EmptyArrays.EMPTY_CLASSES);
value = myPid.invoke(null, EmptyArrays.EMPTY_OBJECTS).toString();
} catch (Throwable t2) {
logger.debug("Could not invoke Process.myPid(); not Android?", t2);
value = "";
}
}
int atIndex = value.indexOf('@');
if (atIndex >= 0) {
value = value.substring(0, atIndex);
}
int pid;
try {
pid = Integer.parseInt(value);
} catch (NumberFormatException e) {
// value did not contain an integer.
pid = -1;
}
if (pid < 0) {
pid = PlatformDependent.threadLocalRandom().nextInt();
logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
}
return pid;
}
static int defaultProcessId() {
ClassLoader loader = PlatformDependent.getClassLoader(DefaultChannelId.class);
int processId = processHandlePid(loader);
if (processId != -1) {
return processId;
}
return jmxPid(loader);
}
private final byte[] data;
private final int hashCode;
private transient String shortValue;
private transient String longValue;
/**
* Visible for testing
*/
DefaultChannelId(final byte[] machineId, final int processId, final int sequence,
final long timestamp, final int random) {
final byte[] data = new byte[machineId.length + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN];
int i = 0;
// machineId
System.arraycopy(machineId, 0, data, i, machineId.length);
i += machineId.length;
// processId
writeInt(data, i, processId);
i += Integer.BYTES;
// sequence
writeInt(data, i, sequence);
i += Integer.BYTES;
// timestamp (kind of)
writeLong(data, i, timestamp);
i += Long.BYTES;
// random
writeInt(data, i, random);
i += Integer.BYTES;
assert i == data.length;
this.data = data;
hashCode = Arrays.hashCode(data);
}
private static void writeInt(byte[] data, int i, int value) {
if (PlatformDependent.isUnaligned()) {
PlatformDependent.putInt(data, i, BIG_ENDIAN_NATIVE_ORDER ? value : Integer.reverseBytes(value));
return;
}
data[i] = (byte) (value >>> 24);
data[i + 1] = (byte) (value >>> 16);
data[i + 2] = (byte) (value >>> 8);
data[i + 3] = (byte) value;
}
private static void writeLong(byte[] data, int i, long value) {
if (PlatformDependent.isUnaligned()) {
PlatformDependent.putLong(data, i, BIG_ENDIAN_NATIVE_ORDER ? value : Long.reverseBytes(value));
return;
}
data[i] = (byte) (value >>> 56);
data[i + 1] = (byte) (value >>> 48);
data[i + 2] = (byte) (value >>> 40);
data[i + 3] = (byte) (value >>> 32);
data[i + 4] = (byte) (value >>> 24);
data[i + 5] = (byte) (value >>> 16);
data[i + 6] = (byte) (value >>> 8);
data[i + 7] = (byte) value;
}
@Override
public String asShortText() {
String shortValue = this.shortValue;
if (shortValue == null) {
this.shortValue = shortValue = ByteBufUtil.hexDump(data, data.length - RANDOM_LEN, RANDOM_LEN);
}
return shortValue;
}
@Override
public String asLongText() {
String longValue = this.longValue;
if (longValue == null) {
this.longValue = longValue = newLongValue();
}
return longValue;
}
private String newLongValue() {
final StringBuilder buf = new StringBuilder(2 * data.length + 5);
final int machineIdLen = data.length - PROCESS_ID_LEN - SEQUENCE_LEN - TIMESTAMP_LEN - RANDOM_LEN;
int i = 0;
i = appendHexDumpField(buf, i, machineIdLen);
i = appendHexDumpField(buf, i, PROCESS_ID_LEN);
i = appendHexDumpField(buf, i, SEQUENCE_LEN);
i = appendHexDumpField(buf, i, TIMESTAMP_LEN);
i = appendHexDumpField(buf, i, RANDOM_LEN);
assert i == data.length;
return buf.substring(0, buf.length() - 1);
}
private int appendHexDumpField(StringBuilder buf, int i, int length) {
buf.append(ByteBufUtil.hexDump(data, i, length));
buf.append('-');
i += length;
return i;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public int compareTo(final ChannelId o) {
if (this == o) {
// short circuit
return 0;
}
if (o instanceof DefaultChannelId) {
// lexicographic comparison
final byte[] otherData = ((DefaultChannelId) o).data;
int len1 = data.length;
int len2 = otherData.length;
int len = Math.min(len1, len2);
for (int k = 0; k < len; k++) {
byte x = data[k];
byte y = otherData[k];
if (x != y) {
// treat these as unsigned bytes for comparison
return (x & 0xff) - (y & 0xff);
}
}
return len1 - len2;
}
return asLongText().compareTo(o.asLongText());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DefaultChannelId)) {
return false;
}
DefaultChannelId other = (DefaultChannelId) obj;
return hashCode == other.hashCode && Arrays.equals(data, other.data);
}
@Override
public String toString() {
return asShortText();
}
}
| sullis/netty | transport/src/main/java/io/netty/channel/DefaultChannelId.java | 3,496 | // value did not contain an integer. | line_comment | nl | /*
* Copyright 2013 The Netty Project
*
* The Netty Project 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:
*
* 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 io.netty.channel;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.MacAddressUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import static io.netty.util.internal.MacAddressUtil.defaultMachineId;
import static io.netty.util.internal.MacAddressUtil.parseMAC;
import static io.netty.util.internal.PlatformDependent.BIG_ENDIAN_NATIVE_ORDER;
/**
* The default {@link ChannelId} implementation.
*/
public final class DefaultChannelId implements ChannelId {
private static final long serialVersionUID = 3884076183504074063L;
private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class);
private static final byte[] MACHINE_ID;
private static final int PROCESS_ID_LEN = 4;
private static final int PROCESS_ID;
private static final int SEQUENCE_LEN = 4;
private static final int TIMESTAMP_LEN = 8;
private static final int RANDOM_LEN = 4;
private static final AtomicInteger nextSequence = new AtomicInteger();
/**
* Returns a new {@link DefaultChannelId} instance.
*/
public static DefaultChannelId newInstance() {
return new DefaultChannelId(MACHINE_ID,
PROCESS_ID,
nextSequence.getAndIncrement(),
Long.reverse(System.nanoTime()) ^ System.currentTimeMillis(),
PlatformDependent.threadLocalRandom().nextInt());
}
static {
int processId = -1;
String customProcessId = SystemPropertyUtil.get("io.netty.processId");
if (customProcessId != null) {
try {
processId = Integer.parseInt(customProcessId);
} catch (NumberFormatException e) {
// Malformed input.
}
if (processId < 0) {
processId = -1;
logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId);
} else if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.processId: {} (user-set)", processId);
}
}
if (processId < 0) {
processId = defaultProcessId();
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.processId: {} (auto-detected)", processId);
}
}
PROCESS_ID = processId;
byte[] machineId = null;
String customMachineId = SystemPropertyUtil.get("io.netty.machineId");
if (customMachineId != null) {
try {
machineId = parseMAC(customMachineId);
} catch (Exception e) {
logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId, e);
}
if (machineId != null) {
logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId);
}
}
if (machineId == null) {
machineId = defaultMachineId();
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.machineId: {} (auto-detected)", MacAddressUtil.formatAddress(machineId));
}
}
MACHINE_ID = machineId;
}
static int processHandlePid(ClassLoader loader) {
// pid is positive on unix, non{-1,0} on windows
int nilValue = -1;
if (PlatformDependent.javaVersion() >= 9) {
Long pid;
try {
Class<?> processHandleImplType = Class.forName("java.lang.ProcessHandle", true, loader);
Method processHandleCurrent = processHandleImplType.getMethod("current");
Object processHandleInstance = processHandleCurrent.invoke(null);
Method processHandlePid = processHandleImplType.getMethod("pid");
pid = (Long) processHandlePid.invoke(processHandleInstance);
} catch (Exception e) {
logger.debug("Could not invoke ProcessHandle.current().pid();", e);
return nilValue;
}
if (pid > Integer.MAX_VALUE || pid < Integer.MIN_VALUE) {
throw new IllegalStateException("Current process ID exceeds int range: " + pid);
}
return pid.intValue();
}
return nilValue;
}
static int jmxPid(ClassLoader loader) {
String value;
try {
// Invoke java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
Class<?> mgmtFactoryType = Class.forName("java.lang.management.ManagementFactory", true, loader);
Class<?> runtimeMxBeanType = Class.forName("java.lang.management.RuntimeMXBean", true, loader);
Method getRuntimeMXBean = mgmtFactoryType.getMethod("getRuntimeMXBean", EmptyArrays.EMPTY_CLASSES);
Object bean = getRuntimeMXBean.invoke(null, EmptyArrays.EMPTY_OBJECTS);
Method getName = runtimeMxBeanType.getMethod("getName", EmptyArrays.EMPTY_CLASSES);
value = (String) getName.invoke(bean, EmptyArrays.EMPTY_OBJECTS);
} catch (Throwable t) {
logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(); Android?", t);
try {
// Invoke android.os.Process.myPid()
Class<?> processType = Class.forName("android.os.Process", true, loader);
Method myPid = processType.getMethod("myPid", EmptyArrays.EMPTY_CLASSES);
value = myPid.invoke(null, EmptyArrays.EMPTY_OBJECTS).toString();
} catch (Throwable t2) {
logger.debug("Could not invoke Process.myPid(); not Android?", t2);
value = "";
}
}
int atIndex = value.indexOf('@');
if (atIndex >= 0) {
value = value.substring(0, atIndex);
}
int pid;
try {
pid = Integer.parseInt(value);
} catch (NumberFormatException e) {
// value did<SUF>
pid = -1;
}
if (pid < 0) {
pid = PlatformDependent.threadLocalRandom().nextInt();
logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
}
return pid;
}
static int defaultProcessId() {
ClassLoader loader = PlatformDependent.getClassLoader(DefaultChannelId.class);
int processId = processHandlePid(loader);
if (processId != -1) {
return processId;
}
return jmxPid(loader);
}
private final byte[] data;
private final int hashCode;
private transient String shortValue;
private transient String longValue;
/**
* Visible for testing
*/
DefaultChannelId(final byte[] machineId, final int processId, final int sequence,
final long timestamp, final int random) {
final byte[] data = new byte[machineId.length + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN];
int i = 0;
// machineId
System.arraycopy(machineId, 0, data, i, machineId.length);
i += machineId.length;
// processId
writeInt(data, i, processId);
i += Integer.BYTES;
// sequence
writeInt(data, i, sequence);
i += Integer.BYTES;
// timestamp (kind of)
writeLong(data, i, timestamp);
i += Long.BYTES;
// random
writeInt(data, i, random);
i += Integer.BYTES;
assert i == data.length;
this.data = data;
hashCode = Arrays.hashCode(data);
}
private static void writeInt(byte[] data, int i, int value) {
if (PlatformDependent.isUnaligned()) {
PlatformDependent.putInt(data, i, BIG_ENDIAN_NATIVE_ORDER ? value : Integer.reverseBytes(value));
return;
}
data[i] = (byte) (value >>> 24);
data[i + 1] = (byte) (value >>> 16);
data[i + 2] = (byte) (value >>> 8);
data[i + 3] = (byte) value;
}
private static void writeLong(byte[] data, int i, long value) {
if (PlatformDependent.isUnaligned()) {
PlatformDependent.putLong(data, i, BIG_ENDIAN_NATIVE_ORDER ? value : Long.reverseBytes(value));
return;
}
data[i] = (byte) (value >>> 56);
data[i + 1] = (byte) (value >>> 48);
data[i + 2] = (byte) (value >>> 40);
data[i + 3] = (byte) (value >>> 32);
data[i + 4] = (byte) (value >>> 24);
data[i + 5] = (byte) (value >>> 16);
data[i + 6] = (byte) (value >>> 8);
data[i + 7] = (byte) value;
}
@Override
public String asShortText() {
String shortValue = this.shortValue;
if (shortValue == null) {
this.shortValue = shortValue = ByteBufUtil.hexDump(data, data.length - RANDOM_LEN, RANDOM_LEN);
}
return shortValue;
}
@Override
public String asLongText() {
String longValue = this.longValue;
if (longValue == null) {
this.longValue = longValue = newLongValue();
}
return longValue;
}
private String newLongValue() {
final StringBuilder buf = new StringBuilder(2 * data.length + 5);
final int machineIdLen = data.length - PROCESS_ID_LEN - SEQUENCE_LEN - TIMESTAMP_LEN - RANDOM_LEN;
int i = 0;
i = appendHexDumpField(buf, i, machineIdLen);
i = appendHexDumpField(buf, i, PROCESS_ID_LEN);
i = appendHexDumpField(buf, i, SEQUENCE_LEN);
i = appendHexDumpField(buf, i, TIMESTAMP_LEN);
i = appendHexDumpField(buf, i, RANDOM_LEN);
assert i == data.length;
return buf.substring(0, buf.length() - 1);
}
private int appendHexDumpField(StringBuilder buf, int i, int length) {
buf.append(ByteBufUtil.hexDump(data, i, length));
buf.append('-');
i += length;
return i;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public int compareTo(final ChannelId o) {
if (this == o) {
// short circuit
return 0;
}
if (o instanceof DefaultChannelId) {
// lexicographic comparison
final byte[] otherData = ((DefaultChannelId) o).data;
int len1 = data.length;
int len2 = otherData.length;
int len = Math.min(len1, len2);
for (int k = 0; k < len; k++) {
byte x = data[k];
byte y = otherData[k];
if (x != y) {
// treat these as unsigned bytes for comparison
return (x & 0xff) - (y & 0xff);
}
}
return len1 - len2;
}
return asLongText().compareTo(o.asLongText());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DefaultChannelId)) {
return false;
}
DefaultChannelId other = (DefaultChannelId) obj;
return hashCode == other.hashCode && Arrays.equals(data, other.data);
}
@Override
public String toString() {
return asShortText();
}
}
|
124313_8 | package com.yc.english.vip.views.fragments;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.yc.english.R;
import com.yc.english.base.view.BaseFragment;
import com.yc.english.pay.PayConfig;
import com.yc.english.pay.PayWayInfo;
import com.yc.english.setting.model.bean.GoodInfo;
import com.yc.english.setting.model.bean.GoodInfoWrapper;
import com.yc.english.vip.model.bean.GoodsType;
import com.yc.english.vip.utils.VipInfoHelper;
import com.yc.english.weixin.model.domain.CourseInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.functions.Action1;
/**
* Created by wanglin on 2017/11/27 14:46.
*/
public class BaseVipPayFragment extends BaseFragment {
@BindView(R.id.baseItemView_ceping)
BasePayItemView baseItemViewCeping;
@BindView(R.id.tv_vip_three_month)
TextView tvVipThreeMonth;
@BindView(R.id.tv_vip_six_month)
TextView tvVipSixMonth;
@BindView(R.id.tv_vip_tween_month)
TextView tvVipTweenMonth;
@BindView(R.id.tv_vip_forever)
TextView tvVipForever;
@BindView(R.id.iv_vip_price)
ImageView ivVipPrice;
@BindView(R.id.vip_current_price)
TextView vipCurrentPrice;
@BindView(R.id.tv_vip_original_price)
TextView tvVipOriginalPrice;
@BindView(R.id.ll_vip_ali)
LinearLayout llVipAli;
@BindView(R.id.ll_vip_wx)
LinearLayout llVipWx;
@BindView(R.id.ll_first_content)
LinearLayout llFirstContent;
@BindView(R.id.baseItemView_union)
BasePayItemView baseItemViewUnion;
@BindView(R.id.rootView)
LinearLayout rootView;
@BindView(R.id.ll_right_container)
LinearLayout llRightContainer;
@BindView(R.id.ll_month_container)
LinearLayout llMonthContainer;
@BindView(R.id.baseItemView_weike)
BasePayItemView baseItemViewWeike;
@BindView(R.id.baseItemView_teach)
BasePayItemView baseItemViewTeach;
@BindView(R.id.baseItemView_plan)
BasePayItemView baseItemViewPlan;
@BindView(R.id.baseItemView_task_tutorship)
BasePayItemView baseItemViewTaskTutorship;
@BindView(R.id.baseItemView_video_fast)
BasePayItemView baseItemViewVideoFast;
@BindView(R.id.vip_price_unit)
TextView vipPriceUnit;
private int mType;//1.提分辅导2.VIP会员3.单次购买
private onVipClickListener mListener;
private List<PayWayInfo> payWayInfoList;
private int position = 0;
private String paywayName = PayConfig.ali_pay;
private GoodInfo goodInfo;
private List<View> viewList = new ArrayList<>();
// private List<GoodInfo> sVipList;//提分辅导
private List<GoodInfo> generalVipList;//普通会员
// private List<GoodInfo> dianduList;//点读
// private List<GoodInfo> weikeList;//微课
private CourseInfo courseInfo;
@Override
public void init() {
baseItemViewCeping.setVisibility(mType == GoodsType.TYPE_GENERAL_VIP ? View.GONE : View.VISIBLE);
baseItemViewPlan.setVisibility(mType == GoodsType.TYPE_SVIP ? View.VISIBLE : View.GONE);
baseItemViewTaskTutorship.setVisibility(mType == GoodsType.TYPE_SVIP ? View.VISIBLE : View.GONE);
GoodInfoWrapper goodInfoWrapper = VipInfoHelper.getGoodInfoWrapper();
// sVipList = goodInfoWrapper.getSvip();
generalVipList = goodInfoWrapper.getVip();
// dianduList = goodInfoWrapper.getDiandu();
// Collections.sort(dianduList, new Comparator<GoodInfo>() {
// @Override
// public int compare(GoodInfo o1, GoodInfo o2) {
// return Integer.parseInt(o1.getUse_time_limit()) - Integer.parseInt(o2.getUse_time_limit());
// }
// });
//
// weikeList = goodInfoWrapper.getWvip();
if (mType == GoodsType.TYPE_SVIP) {
tvVipThreeMonth.setText("1个月");
tvVipSixMonth.setText("3个月");
tvVipTweenMonth.setText("6个月");
tvVipForever.setVisibility(View.INVISIBLE);
// setGoodInfo(position, sVipList);
} else if (mType == GoodsType.TYPE_GENERAL_VIP) {
tvVipThreeMonth.setVisibility(View.GONE);
tvVipSixMonth.setVisibility(View.GONE);
tvVipTweenMonth.setVisibility(View.GONE);
tvVipForever.setText("永久会员");
setTextStyle(tvVipForever);
baseItemViewWeike.setContentAndIcon("微课免费看", 0);
baseItemViewTeach.setContentAndIcon("智能测评", R.mipmap.vip_ceping);
baseItemViewVideoFast.setContentAndIcon("个人学习计划", R.mipmap.vip_plan);
setGoodInfo(position, generalVipList);
} else {
llFirstContent.setVisibility(View.GONE);
baseItemViewUnion.setVisibility(View.GONE);
tvVipTweenMonth.setText("永久会员");
if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
baseItemViewCeping.setContentAndIcon("同步微课", 0);
tvVipForever.setText("单次微课");
// setGoodInfo(position, weikeList);
} else {
if (mType == GoodsType.TYPE_SINGLE_DIANDU) {
tvVipThreeMonth.setText("1个月");
tvVipSixMonth.setText("3个月");
tvVipTweenMonth.setText("6个月");
tvVipForever.setText("永久会员");
baseItemViewCeping.setContentAndIcon("教材点读", 0);
// setGoodInfo(position, dianduList);
} else if (mType == GoodsType.TYPE_SINGLE_INDIVIDUALITY_PLAN) {
tvVipForever.setVisibility(View.GONE);
baseItemViewCeping.setContentAndIcon("个性学习计划", 0);
}
}
LinearLayout.MarginLayoutParams layoutParams = (LinearLayout.MarginLayoutParams) llRightContainer.getLayoutParams();
layoutParams.topMargin = SizeUtils.dp2px(15);
llRightContainer.setLayoutParams(layoutParams);
rootView.setGravity(Gravity.TOP);
// if (getCourserInfo() != null) {
// vipCurrentPrice.setText(String.valueOf(getCourserInfo().getMPrice()));
// tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), String.valueOf(getCourserInfo().getPrice())));
// }
}
// setTextStyle(tvVipThreeMonth);
tvVipOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
viewList.add(llVipWx);
viewList.add(llVipAli);
setPayWayInfo(0);
initListener();
}
private void initListener() {
click(tvVipThreeMonth, 0);
click(tvVipSixMonth, 1);
click(tvVipTweenMonth, 2);
click(tvVipForever, 3);
click(llVipWx, 0);
click(llVipAli, 1);
}
@Override
public int getLayoutId() {
return R.layout.base_vip_right;
}
private void restoreTextViewBg() {
tvVipThreeMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipSixMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipTweenMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipForever.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipThreeMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipSixMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipTweenMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipForever.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
}
public void setType(int type) {
this.mType = type;
}
private void setTextStyle(TextView tv) {
restoreTextViewBg();
tv.setBackgroundResource(R.drawable.vip_item_select_time);
tv.setTextColor(ContextCompat.getColor(getActivity(), R.color.group_blue_21b5f8));
}
public void setCourseInfo(CourseInfo courseInfo) {
this.courseInfo = courseInfo;
}
public interface onVipClickListener {
void onVipClick(GoodInfo goodInfo, String payWayName, int type);
}
public void setOnVipClickListener(onVipClickListener mListener) {
this.mListener = mListener;
}
private void setGoodInfo(int position, List<GoodInfo> goodInfoList) {
if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
if (position == 3) {
if (courseInfo != null) {
vipCurrentPrice.setText(String.valueOf(courseInfo.getMPrice()));
tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), String.valueOf(courseInfo.getPrice())));
goodInfo = new GoodInfo();
goodInfo.setId(courseInfo.getGoodId());
goodInfo.setM_price(String.valueOf(courseInfo.getMPrice()));
goodInfo.setPay_price(String.valueOf(courseInfo.getPayPrice()));
goodInfo.setType_id(courseInfo.getType_id());
goodInfo.setName(courseInfo.getTitle());
}
} else {
setGoodVipInfo(position, goodInfoList);
}
return;
}
setGoodVipInfo(position, goodInfoList);
}
private void setGoodVipInfo(int position, List<GoodInfo> goodInfoList) {
if (goodInfoList != null && position < goodInfoList.size()) {
goodInfo = goodInfoList.get(position);
String payPrice = goodInfo.getPay_price();
int realPrice = (int) (Float.parseFloat(payPrice));
vipCurrentPrice.setText(payPrice);
tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), goodInfo.getPrice()));
}
}
private void setPayWayInfo(int position) {
for (View view : viewList) {
view.setBackgroundResource(R.drawable.vip_item_unselect_time);
}
payWayInfoList = new ArrayList<>();
payWayInfoList.add(new PayWayInfo(PayConfig.wx_pay));
payWayInfoList.add(new PayWayInfo(PayConfig.ali_pay));
viewList.get(position).setBackgroundResource(R.drawable.vip_item_select_time);
paywayName = payWayInfoList.get(position).getPay_way_name();
}
private void click(final View view, final int position) {
RxView.clicks(view).throttleFirst(200, TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
if (view instanceof TextView) {
setTextStyle(((TextView) view));
if (mType == GoodsType.TYPE_SVIP) {
// setGoodInfo(position, sVipList);
} else if (mType == GoodsType.TYPE_GENERAL_VIP) {
setGoodInfo(position, generalVipList);
} else if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
// setGoodInfo(position, weikeList);
} else if (mType == GoodsType.TYPE_SINGLE_DIANDU) {
// setGoodInfo(position, dianduList);
}
}
if (view instanceof LinearLayout) {
setPayWayInfo(position);
}
if (mListener != null) {
mListener.onVipClick(goodInfo, paywayName, mType);
}
}
});
}
}
| sunshey/english | app/src/main/java/com/yc/english/vip/views/fragments/BaseVipPayFragment.java | 3,868 | // return Integer.parseInt(o1.getUse_time_limit()) - Integer.parseInt(o2.getUse_time_limit()); | line_comment | nl | package com.yc.english.vip.views.fragments;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.yc.english.R;
import com.yc.english.base.view.BaseFragment;
import com.yc.english.pay.PayConfig;
import com.yc.english.pay.PayWayInfo;
import com.yc.english.setting.model.bean.GoodInfo;
import com.yc.english.setting.model.bean.GoodInfoWrapper;
import com.yc.english.vip.model.bean.GoodsType;
import com.yc.english.vip.utils.VipInfoHelper;
import com.yc.english.weixin.model.domain.CourseInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.functions.Action1;
/**
* Created by wanglin on 2017/11/27 14:46.
*/
public class BaseVipPayFragment extends BaseFragment {
@BindView(R.id.baseItemView_ceping)
BasePayItemView baseItemViewCeping;
@BindView(R.id.tv_vip_three_month)
TextView tvVipThreeMonth;
@BindView(R.id.tv_vip_six_month)
TextView tvVipSixMonth;
@BindView(R.id.tv_vip_tween_month)
TextView tvVipTweenMonth;
@BindView(R.id.tv_vip_forever)
TextView tvVipForever;
@BindView(R.id.iv_vip_price)
ImageView ivVipPrice;
@BindView(R.id.vip_current_price)
TextView vipCurrentPrice;
@BindView(R.id.tv_vip_original_price)
TextView tvVipOriginalPrice;
@BindView(R.id.ll_vip_ali)
LinearLayout llVipAli;
@BindView(R.id.ll_vip_wx)
LinearLayout llVipWx;
@BindView(R.id.ll_first_content)
LinearLayout llFirstContent;
@BindView(R.id.baseItemView_union)
BasePayItemView baseItemViewUnion;
@BindView(R.id.rootView)
LinearLayout rootView;
@BindView(R.id.ll_right_container)
LinearLayout llRightContainer;
@BindView(R.id.ll_month_container)
LinearLayout llMonthContainer;
@BindView(R.id.baseItemView_weike)
BasePayItemView baseItemViewWeike;
@BindView(R.id.baseItemView_teach)
BasePayItemView baseItemViewTeach;
@BindView(R.id.baseItemView_plan)
BasePayItemView baseItemViewPlan;
@BindView(R.id.baseItemView_task_tutorship)
BasePayItemView baseItemViewTaskTutorship;
@BindView(R.id.baseItemView_video_fast)
BasePayItemView baseItemViewVideoFast;
@BindView(R.id.vip_price_unit)
TextView vipPriceUnit;
private int mType;//1.提分辅导2.VIP会员3.单次购买
private onVipClickListener mListener;
private List<PayWayInfo> payWayInfoList;
private int position = 0;
private String paywayName = PayConfig.ali_pay;
private GoodInfo goodInfo;
private List<View> viewList = new ArrayList<>();
// private List<GoodInfo> sVipList;//提分辅导
private List<GoodInfo> generalVipList;//普通会员
// private List<GoodInfo> dianduList;//点读
// private List<GoodInfo> weikeList;//微课
private CourseInfo courseInfo;
@Override
public void init() {
baseItemViewCeping.setVisibility(mType == GoodsType.TYPE_GENERAL_VIP ? View.GONE : View.VISIBLE);
baseItemViewPlan.setVisibility(mType == GoodsType.TYPE_SVIP ? View.VISIBLE : View.GONE);
baseItemViewTaskTutorship.setVisibility(mType == GoodsType.TYPE_SVIP ? View.VISIBLE : View.GONE);
GoodInfoWrapper goodInfoWrapper = VipInfoHelper.getGoodInfoWrapper();
// sVipList = goodInfoWrapper.getSvip();
generalVipList = goodInfoWrapper.getVip();
// dianduList = goodInfoWrapper.getDiandu();
// Collections.sort(dianduList, new Comparator<GoodInfo>() {
// @Override
// public int compare(GoodInfo o1, GoodInfo o2) {
// return Integer.parseInt(o1.getUse_time_limit())<SUF>
// }
// });
//
// weikeList = goodInfoWrapper.getWvip();
if (mType == GoodsType.TYPE_SVIP) {
tvVipThreeMonth.setText("1个月");
tvVipSixMonth.setText("3个月");
tvVipTweenMonth.setText("6个月");
tvVipForever.setVisibility(View.INVISIBLE);
// setGoodInfo(position, sVipList);
} else if (mType == GoodsType.TYPE_GENERAL_VIP) {
tvVipThreeMonth.setVisibility(View.GONE);
tvVipSixMonth.setVisibility(View.GONE);
tvVipTweenMonth.setVisibility(View.GONE);
tvVipForever.setText("永久会员");
setTextStyle(tvVipForever);
baseItemViewWeike.setContentAndIcon("微课免费看", 0);
baseItemViewTeach.setContentAndIcon("智能测评", R.mipmap.vip_ceping);
baseItemViewVideoFast.setContentAndIcon("个人学习计划", R.mipmap.vip_plan);
setGoodInfo(position, generalVipList);
} else {
llFirstContent.setVisibility(View.GONE);
baseItemViewUnion.setVisibility(View.GONE);
tvVipTweenMonth.setText("永久会员");
if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
baseItemViewCeping.setContentAndIcon("同步微课", 0);
tvVipForever.setText("单次微课");
// setGoodInfo(position, weikeList);
} else {
if (mType == GoodsType.TYPE_SINGLE_DIANDU) {
tvVipThreeMonth.setText("1个月");
tvVipSixMonth.setText("3个月");
tvVipTweenMonth.setText("6个月");
tvVipForever.setText("永久会员");
baseItemViewCeping.setContentAndIcon("教材点读", 0);
// setGoodInfo(position, dianduList);
} else if (mType == GoodsType.TYPE_SINGLE_INDIVIDUALITY_PLAN) {
tvVipForever.setVisibility(View.GONE);
baseItemViewCeping.setContentAndIcon("个性学习计划", 0);
}
}
LinearLayout.MarginLayoutParams layoutParams = (LinearLayout.MarginLayoutParams) llRightContainer.getLayoutParams();
layoutParams.topMargin = SizeUtils.dp2px(15);
llRightContainer.setLayoutParams(layoutParams);
rootView.setGravity(Gravity.TOP);
// if (getCourserInfo() != null) {
// vipCurrentPrice.setText(String.valueOf(getCourserInfo().getMPrice()));
// tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), String.valueOf(getCourserInfo().getPrice())));
// }
}
// setTextStyle(tvVipThreeMonth);
tvVipOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
viewList.add(llVipWx);
viewList.add(llVipAli);
setPayWayInfo(0);
initListener();
}
private void initListener() {
click(tvVipThreeMonth, 0);
click(tvVipSixMonth, 1);
click(tvVipTweenMonth, 2);
click(tvVipForever, 3);
click(llVipWx, 0);
click(llVipAli, 1);
}
@Override
public int getLayoutId() {
return R.layout.base_vip_right;
}
private void restoreTextViewBg() {
tvVipThreeMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipSixMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipTweenMonth.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipForever.setBackgroundResource(R.drawable.vip_item_unselect_time);
tvVipThreeMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipSixMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipTweenMonth.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
tvVipForever.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333));
}
public void setType(int type) {
this.mType = type;
}
private void setTextStyle(TextView tv) {
restoreTextViewBg();
tv.setBackgroundResource(R.drawable.vip_item_select_time);
tv.setTextColor(ContextCompat.getColor(getActivity(), R.color.group_blue_21b5f8));
}
public void setCourseInfo(CourseInfo courseInfo) {
this.courseInfo = courseInfo;
}
public interface onVipClickListener {
void onVipClick(GoodInfo goodInfo, String payWayName, int type);
}
public void setOnVipClickListener(onVipClickListener mListener) {
this.mListener = mListener;
}
private void setGoodInfo(int position, List<GoodInfo> goodInfoList) {
if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
if (position == 3) {
if (courseInfo != null) {
vipCurrentPrice.setText(String.valueOf(courseInfo.getMPrice()));
tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), String.valueOf(courseInfo.getPrice())));
goodInfo = new GoodInfo();
goodInfo.setId(courseInfo.getGoodId());
goodInfo.setM_price(String.valueOf(courseInfo.getMPrice()));
goodInfo.setPay_price(String.valueOf(courseInfo.getPayPrice()));
goodInfo.setType_id(courseInfo.getType_id());
goodInfo.setName(courseInfo.getTitle());
}
} else {
setGoodVipInfo(position, goodInfoList);
}
return;
}
setGoodVipInfo(position, goodInfoList);
}
private void setGoodVipInfo(int position, List<GoodInfo> goodInfoList) {
if (goodInfoList != null && position < goodInfoList.size()) {
goodInfo = goodInfoList.get(position);
String payPrice = goodInfo.getPay_price();
int realPrice = (int) (Float.parseFloat(payPrice));
vipCurrentPrice.setText(payPrice);
tvVipOriginalPrice.setText(String.format(getString(R.string.original_price), goodInfo.getPrice()));
}
}
private void setPayWayInfo(int position) {
for (View view : viewList) {
view.setBackgroundResource(R.drawable.vip_item_unselect_time);
}
payWayInfoList = new ArrayList<>();
payWayInfoList.add(new PayWayInfo(PayConfig.wx_pay));
payWayInfoList.add(new PayWayInfo(PayConfig.ali_pay));
viewList.get(position).setBackgroundResource(R.drawable.vip_item_select_time);
paywayName = payWayInfoList.get(position).getPay_way_name();
}
private void click(final View view, final int position) {
RxView.clicks(view).throttleFirst(200, TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
if (view instanceof TextView) {
setTextStyle(((TextView) view));
if (mType == GoodsType.TYPE_SVIP) {
// setGoodInfo(position, sVipList);
} else if (mType == GoodsType.TYPE_GENERAL_VIP) {
setGoodInfo(position, generalVipList);
} else if (mType == GoodsType.TYPE_SINGLE_WEIKE) {
// setGoodInfo(position, weikeList);
} else if (mType == GoodsType.TYPE_SINGLE_DIANDU) {
// setGoodInfo(position, dianduList);
}
}
if (view instanceof LinearLayout) {
setPayWayInfo(position);
}
if (mListener != null) {
mListener.onVipClick(goodInfo, paywayName, mType);
}
}
});
}
}
|
120446_33 | /*******************************************************************************
* Copyright 2009, 2017 Martin Davis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.locationtech.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.locationtech.proj4j.datum.Datum;
import org.locationtech.proj4j.datum.Ellipsoid;
import org.locationtech.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*/
public class Registry {
public Registry() {
super();
initialize();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code) {
for (int i = 0; i < datums.length; i++) {
if (datums[i].getCode().equals(code)) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name) {
for (int i = 0; i < ellipsoids.length; i++) {
if (ellipsoids[i].shortName.equals(name)) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register(String name, Class cls, String description) {
projRegistry.put(name, cls);
}
public Projection getProjection(String name) {
// if ( projRegistry == null )
// initialize();
Class cls = (Class) projRegistry.get(name);
if (cls != null) {
try {
Projection projection = (Projection) cls.newInstance();
if (projection != null)
projection.setName(name);
return projection;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
return null;
}
private synchronized void initialize() {
// guard against race condition
if (projRegistry != null)
return;
projRegistry = new HashMap();
register("aea", AlbersProjection.class, "Albers Equal Area");
register("aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant");
register("airy", AiryProjection.class, "Airy");
register("aitoff", AitoffProjection.class, "Aitoff");
register("alsk", Projection.class, "Mod. Stereographics of Alaska");
register("apian", Projection.class, "Apian Globular I");
register("august", AugustProjection.class, "August Epicycloidal");
register("bacon", Projection.class, "Bacon Globular");
register("bipc", BipolarProjection.class, "Bipolar conic of western hemisphere");
register("boggs", BoggsProjection.class, "Boggs Eumorphic");
register("bonne", BonneProjection.class, "Bonne (Werner lat_1=90)");
register("cass", CassiniProjection.class, "Cassini");
register("cc", CentralCylindricalProjection.class, "Central Cylindrical");
register("cea", EqualAreaCylindricalProjection.class, "Equal Area Cylindrical");
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
register("collg", CollignonProjection.class, "Collignon");
register("crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)");
register("denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical");
register("eck1", Eckert1Projection.class, "Eckert I");
register("eck2", Eckert2Projection.class, "Eckert II");
// register( "eck3", Eckert3Projection.class, "Eckert III" );
register("eck4", Eckert4Projection.class, "Eckert IV");
register("eck5", Eckert5Projection.class, "Eckert V");
register("eck6", Eckert6Projection.class, "Eckert VI");
register("eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)");
register("eqdc", EquidistantConicProjection.class, "Equidistant Conic");
register("euler", EulerProjection.class, "Euler");
register("fahey", FaheyProjection.class, "Fahey");
register("fouc", FoucautProjection.class, "Foucaut");
register("fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal");
register("gall", GallProjection.class, "Gall (Gall Stereographic)");
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
register("gnom", GnomonicAzimuthalProjection.class, "Gnomonic");
register("goode", GoodeProjection.class, "Goode Homolosine");
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
register("hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff");
register("hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area");
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
register("kav5", KavraiskyVProjection.class, "Kavraisky V");
// register( "kav7", Projection.class, "Kavraisky VII" );
register("krovak", KrovakProjection.class, "Krovak");
// register( "labrd", Projection.class, "Laborde" );
register("laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area");
register("lagrng", LagrangeProjection.class, "Lagrange");
register("larr", LarriveeProjection.class, "Larrivee");
register("lask", LaskowskiProjection.class, "Laskowski");
register("latlong", LongLatProjection.class, "Lat/Long");
register("longlat", LongLatProjection.class, "Lat/Long");
register("lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic");
register("leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic");
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
register("loxim", LoximuthalProjection.class, "Loximuthal");
register("lsat", LandsatProjection.class, "Space oblique for LANDSAT");
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
register("mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)");
register("mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic");
register("mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic");
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
register("merc", MercatorProjection.class, "Mercator");
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
register("mill", MillerProjection.class, "Miller Cylindrical");
// register( "mpoly", Projection.class, "Modified Polyconic" );
register("moll", MolleweideProjection.class, "Mollweide");
register("murd1", Murdoch1Projection.class, "Murdoch I");
register("murd2", Murdoch2Projection.class, "Murdoch II");
register("murd3", Murdoch3Projection.class, "Murdoch III");
register("nell", NellProjection.class, "Nell");
// register( "nell_h", Projection.class, "Nell-Hammer" );
register("nicol", NicolosiProjection.class, "Nicolosi Globular");
register("nsper", PerspectiveProjection.class, "Near-sided perspective");
register("nzmg", NewZealandMapGridProjection.class, "New Zealand Map Grid");
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
register("omerc", ObliqueMercatorProjection.class, "Oblique Mercator");
// register( "ortel", Projection.class, "Ortelius Oval" );
register("ortho", OrthographicAzimuthalProjection.class, "Orthographic");
register("pconic", PerspectiveConicProjection.class, "Perspective Conic");
register("poly", PolyconicProjection.class, "Polyconic (American)");
// register( "putp1", Projection.class, "Putnins P1" );
register("putp2", PutninsP2Projection.class, "Putnins P2");
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
register("putp4p", PutninsP4Projection.class, "Putnins P4'");
register("putp5", PutninsP5Projection.class, "Putnins P5");
register("putp5p", PutninsP5PProjection.class, "Putnins P5'");
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
register("qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic");
register("robin", RobinsonProjection.class, "Robinson");
register("rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic");
register("sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)");
register("somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator");
register("stere", StereographicAzimuthalProjection.class, "Stereographic");
register("sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative");
register("tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical");
register("tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area");
// register( "tissot", TissotProjection.class, "Tissot Conic" );
register("tmerc", TransverseMercatorProjection.class, "Transverse Mercator");
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
register("urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal");
register("utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)");
register("vandg", VanDerGrintenProjection.class, "van der Grinten (I)");
// register( "vandg2", Projection.class, "van der Grinten II" );
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
register("vitk1", VitkovskyProjection.class, "Vitkovsky I");
register("wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)");
register("wag2", Wagner2Projection.class, "Wagner II");
register("wag3", Wagner3Projection.class, "Wagner III");
register("wag4", Wagner4Projection.class, "Wagner IV");
register("wag5", Wagner5Projection.class, "Wagner V");
// register( "wag6", Projection.class, "Wagner VI" );
register("wag7", Wagner7Projection.class, "Wagner VII");
register("weren", WerenskioldProjection.class, "Werenskiold I");
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
register("wintri", WinkelTripelProjection.class, "Winkel Tripel");
}
}
| super-normal/proj4j | src/main/java/org/locationtech/proj4j/Registry.java | 5,278 | // register( "vandg2", Projection.class, "van der Grinten II" ); | line_comment | nl | /*******************************************************************************
* Copyright 2009, 2017 Martin Davis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.locationtech.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.locationtech.proj4j.datum.Datum;
import org.locationtech.proj4j.datum.Ellipsoid;
import org.locationtech.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*/
public class Registry {
public Registry() {
super();
initialize();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code) {
for (int i = 0; i < datums.length; i++) {
if (datums[i].getCode().equals(code)) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name) {
for (int i = 0; i < ellipsoids.length; i++) {
if (ellipsoids[i].shortName.equals(name)) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register(String name, Class cls, String description) {
projRegistry.put(name, cls);
}
public Projection getProjection(String name) {
// if ( projRegistry == null )
// initialize();
Class cls = (Class) projRegistry.get(name);
if (cls != null) {
try {
Projection projection = (Projection) cls.newInstance();
if (projection != null)
projection.setName(name);
return projection;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
return null;
}
private synchronized void initialize() {
// guard against race condition
if (projRegistry != null)
return;
projRegistry = new HashMap();
register("aea", AlbersProjection.class, "Albers Equal Area");
register("aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant");
register("airy", AiryProjection.class, "Airy");
register("aitoff", AitoffProjection.class, "Aitoff");
register("alsk", Projection.class, "Mod. Stereographics of Alaska");
register("apian", Projection.class, "Apian Globular I");
register("august", AugustProjection.class, "August Epicycloidal");
register("bacon", Projection.class, "Bacon Globular");
register("bipc", BipolarProjection.class, "Bipolar conic of western hemisphere");
register("boggs", BoggsProjection.class, "Boggs Eumorphic");
register("bonne", BonneProjection.class, "Bonne (Werner lat_1=90)");
register("cass", CassiniProjection.class, "Cassini");
register("cc", CentralCylindricalProjection.class, "Central Cylindrical");
register("cea", EqualAreaCylindricalProjection.class, "Equal Area Cylindrical");
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
register("collg", CollignonProjection.class, "Collignon");
register("crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)");
register("denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical");
register("eck1", Eckert1Projection.class, "Eckert I");
register("eck2", Eckert2Projection.class, "Eckert II");
// register( "eck3", Eckert3Projection.class, "Eckert III" );
register("eck4", Eckert4Projection.class, "Eckert IV");
register("eck5", Eckert5Projection.class, "Eckert V");
register("eck6", Eckert6Projection.class, "Eckert VI");
register("eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)");
register("eqdc", EquidistantConicProjection.class, "Equidistant Conic");
register("euler", EulerProjection.class, "Euler");
register("fahey", FaheyProjection.class, "Fahey");
register("fouc", FoucautProjection.class, "Foucaut");
register("fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal");
register("gall", GallProjection.class, "Gall (Gall Stereographic)");
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
register("gnom", GnomonicAzimuthalProjection.class, "Gnomonic");
register("goode", GoodeProjection.class, "Goode Homolosine");
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
register("hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff");
register("hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area");
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
register("kav5", KavraiskyVProjection.class, "Kavraisky V");
// register( "kav7", Projection.class, "Kavraisky VII" );
register("krovak", KrovakProjection.class, "Krovak");
// register( "labrd", Projection.class, "Laborde" );
register("laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area");
register("lagrng", LagrangeProjection.class, "Lagrange");
register("larr", LarriveeProjection.class, "Larrivee");
register("lask", LaskowskiProjection.class, "Laskowski");
register("latlong", LongLatProjection.class, "Lat/Long");
register("longlat", LongLatProjection.class, "Lat/Long");
register("lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic");
register("leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic");
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
register("loxim", LoximuthalProjection.class, "Loximuthal");
register("lsat", LandsatProjection.class, "Space oblique for LANDSAT");
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
register("mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)");
register("mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic");
register("mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic");
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
register("merc", MercatorProjection.class, "Mercator");
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
register("mill", MillerProjection.class, "Miller Cylindrical");
// register( "mpoly", Projection.class, "Modified Polyconic" );
register("moll", MolleweideProjection.class, "Mollweide");
register("murd1", Murdoch1Projection.class, "Murdoch I");
register("murd2", Murdoch2Projection.class, "Murdoch II");
register("murd3", Murdoch3Projection.class, "Murdoch III");
register("nell", NellProjection.class, "Nell");
// register( "nell_h", Projection.class, "Nell-Hammer" );
register("nicol", NicolosiProjection.class, "Nicolosi Globular");
register("nsper", PerspectiveProjection.class, "Near-sided perspective");
register("nzmg", NewZealandMapGridProjection.class, "New Zealand Map Grid");
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
register("omerc", ObliqueMercatorProjection.class, "Oblique Mercator");
// register( "ortel", Projection.class, "Ortelius Oval" );
register("ortho", OrthographicAzimuthalProjection.class, "Orthographic");
register("pconic", PerspectiveConicProjection.class, "Perspective Conic");
register("poly", PolyconicProjection.class, "Polyconic (American)");
// register( "putp1", Projection.class, "Putnins P1" );
register("putp2", PutninsP2Projection.class, "Putnins P2");
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
register("putp4p", PutninsP4Projection.class, "Putnins P4'");
register("putp5", PutninsP5Projection.class, "Putnins P5");
register("putp5p", PutninsP5PProjection.class, "Putnins P5'");
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
register("qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic");
register("robin", RobinsonProjection.class, "Robinson");
register("rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic");
register("sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)");
register("somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator");
register("stere", StereographicAzimuthalProjection.class, "Stereographic");
register("sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative");
register("tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical");
register("tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area");
// register( "tissot", TissotProjection.class, "Tissot Conic" );
register("tmerc", TransverseMercatorProjection.class, "Transverse Mercator");
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
register("urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal");
register("utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)");
register("vandg", VanDerGrintenProjection.class, "van der Grinten (I)");
// register( "vandg2",<SUF>
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
register("vitk1", VitkovskyProjection.class, "Vitkovsky I");
register("wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)");
register("wag2", Wagner2Projection.class, "Wagner II");
register("wag3", Wagner3Projection.class, "Wagner III");
register("wag4", Wagner4Projection.class, "Wagner IV");
register("wag5", Wagner5Projection.class, "Wagner V");
// register( "wag6", Projection.class, "Wagner VI" );
register("wag7", Wagner7Projection.class, "Wagner VII");
register("weren", WerenskioldProjection.class, "Werenskiold I");
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
register("wintri", WinkelTripelProjection.class, "Winkel Tripel");
}
}
|
23990_0 | package eu.insertcode.wordgames;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import eu.insertcode.wordgames.games.WordGame;
import static org.bukkit.ChatColor.translateAlternateColorCodes;
/**
* @author Maarten de Goede - insertCode.eu
* Main class
*/
public class Main extends JavaPlugin implements Listener {
ArrayList<WordGame> wordGames = new ArrayList<>();
private Reflection reflection;
/**
* Gets a message from the config and puts it in an array.
* @param path The path to the message.
* @return A coloured String array.
*/
public static String[] getMessages(String path) {
FileConfiguration msgConfig = ConfigManager.getMessages();
String[] messages;
messages = ConfigManager.getMessages().isList(path)
? msgConfig.getStringList(path).toArray(new String[0]) : new String[]{msgConfig.getString(path)};
for (int i = 0; i < messages.length; i++) {
messages[i] = messages[i].replace("{plugin}", msgConfig.getString("variables.plugin"));
}
return messages;
}
public static String[] getColouredMessages(String path) {
String[] messages = getMessages(path);
for (int i = 0; i < messages.length; i++) {
messages[i] = translateAlternateColorCodes('&', messages[i]);
}
return messages;
}
private boolean setup() {
try {
reflection = new Reflection();
getLogger().info("[WordGames+, insertCode] Your server is running " + reflection.getVersion());
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
void reload() {
ConfigManager.reloadMessages();
reloadConfig();
}
public Reflection getReflection() {
return reflection;
}
public void removeGame(WordGame game) {
wordGames.remove(game);
}
@Override
public void onEnable() {
if (setup()) {
// Register the plugin events in this class
getServer().getPluginManager().registerEvents(this, this);
ConfigManager.createFiles(this);
getCommand("wordgame").setExecutor(new CommandHandler(this));
AutoStart.setPlugin(this);
AutoStart.autoStart(); // Start the autoStart scheduler.
} else {
getLogger().severe("Failed to setup WordGames+!");
getLogger().severe("Your server version is not compatible with this plugin!");
Bukkit.getPluginManager().disablePlugin(this);
}
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player p = e.getPlayer();
for (WordGame game : wordGames) {
if (Permission.PLAY_ALL.forPlayer(p, game.getPlayPermission()))
game.onPlayerChat(e);
else for (String message : getColouredMessages("error.noPlayPermissions"))
p.sendMessage(message);
}
}
}
| supertassu/WordGamesPlus | src/main/java/eu/insertcode/wordgames/Main.java | 929 | /**
* @author Maarten de Goede - insertCode.eu
* Main class
*/ | block_comment | nl | package eu.insertcode.wordgames;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import eu.insertcode.wordgames.games.WordGame;
import static org.bukkit.ChatColor.translateAlternateColorCodes;
/**
* @author Maarten de<SUF>*/
public class Main extends JavaPlugin implements Listener {
ArrayList<WordGame> wordGames = new ArrayList<>();
private Reflection reflection;
/**
* Gets a message from the config and puts it in an array.
* @param path The path to the message.
* @return A coloured String array.
*/
public static String[] getMessages(String path) {
FileConfiguration msgConfig = ConfigManager.getMessages();
String[] messages;
messages = ConfigManager.getMessages().isList(path)
? msgConfig.getStringList(path).toArray(new String[0]) : new String[]{msgConfig.getString(path)};
for (int i = 0; i < messages.length; i++) {
messages[i] = messages[i].replace("{plugin}", msgConfig.getString("variables.plugin"));
}
return messages;
}
public static String[] getColouredMessages(String path) {
String[] messages = getMessages(path);
for (int i = 0; i < messages.length; i++) {
messages[i] = translateAlternateColorCodes('&', messages[i]);
}
return messages;
}
private boolean setup() {
try {
reflection = new Reflection();
getLogger().info("[WordGames+, insertCode] Your server is running " + reflection.getVersion());
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
void reload() {
ConfigManager.reloadMessages();
reloadConfig();
}
public Reflection getReflection() {
return reflection;
}
public void removeGame(WordGame game) {
wordGames.remove(game);
}
@Override
public void onEnable() {
if (setup()) {
// Register the plugin events in this class
getServer().getPluginManager().registerEvents(this, this);
ConfigManager.createFiles(this);
getCommand("wordgame").setExecutor(new CommandHandler(this));
AutoStart.setPlugin(this);
AutoStart.autoStart(); // Start the autoStart scheduler.
} else {
getLogger().severe("Failed to setup WordGames+!");
getLogger().severe("Your server version is not compatible with this plugin!");
Bukkit.getPluginManager().disablePlugin(this);
}
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player p = e.getPlayer();
for (WordGame game : wordGames) {
if (Permission.PLAY_ALL.forPlayer(p, game.getPlayPermission()))
game.onPlayerChat(e);
else for (String message : getColouredMessages("error.noPlayPermissions"))
p.sendMessage(message);
}
}
}
|
98679_1 | /*
* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* 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 io.supertokens.config;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.supertokens.Main;
import io.supertokens.cliOptions.CLIOptions;
import io.supertokens.config.annotations.ConfigYamlOnly;
import io.supertokens.config.annotations.IgnoreForAnnotationCheck;
import io.supertokens.config.annotations.NotConflictingInApp;
import io.supertokens.pluginInterface.LOG_LEVEL;
import io.supertokens.pluginInterface.exceptions.InvalidConfigException;
import io.supertokens.utils.SemVer;
import io.supertokens.webserver.Utils;
import io.supertokens.webserver.WebserverAPI;
import jakarta.servlet.ServletException;
import org.apache.catalina.filters.RemoteAddrFilter;
import org.jetbrains.annotations.TestOnly;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.PatternSyntaxException;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CoreConfig {
@IgnoreForAnnotationCheck
public static final String[] PROTECTED_CONFIGS = new String[]{
"ip_allow_regex",
"ip_deny_regex",
};
@IgnoreForAnnotationCheck
@JsonProperty
private int core_config_version = -1;
@NotConflictingInApp
@JsonProperty
private long access_token_validity = 3600; // in seconds
@NotConflictingInApp
@JsonProperty
private boolean access_token_blacklisting = false;
@NotConflictingInApp
@JsonProperty
private double refresh_token_validity = 60 * 2400; // in mins
@IgnoreForAnnotationCheck
@JsonProperty
private long password_reset_token_lifetime = 3600000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private long email_verification_token_lifetime = 24 * 3600 * 1000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private int passwordless_max_code_input_attempts = 5;
@IgnoreForAnnotationCheck
@JsonProperty
private long passwordless_code_lifetime = 900000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private int totp_max_attempts = 5;
@IgnoreForAnnotationCheck
@JsonProperty
private int totp_rate_limit_cooldown_sec = 900; // in seconds (Default 15 mins)
@IgnoreForAnnotationCheck
private final String logDefault = "asdkfahbdfk3kjHS";
@ConfigYamlOnly
@JsonProperty
private String info_log_path = logDefault;
@ConfigYamlOnly
@JsonProperty
private String error_log_path = logDefault;
@NotConflictingInApp
@JsonProperty
private boolean access_token_signing_key_dynamic = true;
@NotConflictingInApp
@JsonProperty("access_token_dynamic_signing_key_update_interval")
@JsonAlias({"access_token_dynamic_signing_key_update_interval", "access_token_signing_key_update_interval"})
private double access_token_dynamic_signing_key_update_interval = 168; // in hours
@ConfigYamlOnly
@JsonProperty
private int port = 3567;
@ConfigYamlOnly
@JsonProperty
private String host = "localhost";
@ConfigYamlOnly
@JsonProperty
private int max_server_pool_size = 10;
@NotConflictingInApp
@JsonProperty
private String api_keys = null;
@NotConflictingInApp
@JsonProperty
private boolean disable_telemetry = false;
@NotConflictingInApp
@JsonProperty
private String password_hashing_alg = "BCRYPT";
@ConfigYamlOnly
@JsonProperty
private int argon2_iterations = 1;
@ConfigYamlOnly
@JsonProperty
private int argon2_memory_kb = 87795; // 85 mb
@ConfigYamlOnly
@JsonProperty
private int argon2_parallelism = 2;
@ConfigYamlOnly
@JsonProperty
private int argon2_hashing_pool_size = 1;
@ConfigYamlOnly
@JsonProperty
private int firebase_password_hashing_pool_size = 1;
@ConfigYamlOnly
@JsonProperty
private int bcrypt_log_rounds = 11;
// TODO: add https in later version
// # (OPTIONAL) boolean value (true or false). Set to true if you want to enable
// https requests to SuperTokens.
// # If you are not running SuperTokens within a closed network along with your
// API process, for
// # example if you are using multiple cloud vendors, then it is recommended to
// set this to true.
// # webserver_https_enabled:
@ConfigYamlOnly
@JsonProperty
private boolean webserver_https_enabled = false;
@ConfigYamlOnly
@JsonProperty
private String base_path = "";
@ConfigYamlOnly
@JsonProperty
private String log_level = "INFO";
@NotConflictingInApp
@JsonProperty
private String firebase_password_hashing_signer_key = null;
@IgnoreForAnnotationCheck
@JsonProperty
private String ip_allow_regex = null;
@IgnoreForAnnotationCheck
@JsonProperty
private String ip_deny_regex = null;
@ConfigYamlOnly
@JsonProperty
private String supertokens_saas_secret = null;
@NotConflictingInApp
@JsonProperty
private String supertokens_max_cdi_version = null;
@ConfigYamlOnly
@JsonProperty
private String supertokens_saas_load_only_cud = null;
@IgnoreForAnnotationCheck
private Set<LOG_LEVEL> allowedLogLevels = null;
@IgnoreForAnnotationCheck
private boolean isNormalizedAndValid = false;
public static Set<String> getValidFields() {
CoreConfig coreConfig = new CoreConfig();
JsonObject coreConfigObj = new GsonBuilder().serializeNulls().create().toJsonTree(coreConfig).getAsJsonObject();
Set<String> validFields = new HashSet<>();
for (Map.Entry<String, JsonElement> entry : coreConfigObj.entrySet()) {
validFields.add(entry.getKey());
}
// Adding the aliases
validFields.add("access_token_signing_key_update_interval");
return validFields;
}
public String getIpAllowRegex() {
return ip_allow_regex;
}
public String getIpDenyRegex() {
return ip_deny_regex;
}
public Set<LOG_LEVEL> getLogLevels(Main main) {
if (allowedLogLevels != null) {
return allowedLogLevels;
}
LOG_LEVEL logLevel = LOG_LEVEL.valueOf(this.log_level);
allowedLogLevels = new HashSet<>();
if (logLevel == LOG_LEVEL.NONE) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.ERROR);
if (logLevel == LOG_LEVEL.ERROR) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.WARN);
if (logLevel == LOG_LEVEL.WARN) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.INFO);
if (logLevel == LOG_LEVEL.INFO) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.DEBUG);
return allowedLogLevels;
}
public String getBasePath() {
return base_path;
}
public String getSuperTokensLoadOnlyCUD() {
return supertokens_saas_load_only_cud;
}
public enum PASSWORD_HASHING_ALG {
ARGON2, BCRYPT, FIREBASE_SCRYPT
}
public int getArgon2HashingPoolSize() {
return argon2_hashing_pool_size;
}
public int getFirebaseSCryptPasswordHashingPoolSize() {
return firebase_password_hashing_pool_size;
}
public int getArgon2Iterations() {
return argon2_iterations;
}
public int getBcryptLogRounds() {
return bcrypt_log_rounds;
}
public int getArgon2MemoryKb() {
return argon2_memory_kb;
}
public int getArgon2Parallelism() {
return argon2_parallelism;
}
public String getFirebase_password_hashing_signer_key() {
if (firebase_password_hashing_signer_key == null) {
throw new IllegalStateException("'firebase_password_hashing_signer_key' cannot be null");
}
return firebase_password_hashing_signer_key;
}
public PASSWORD_HASHING_ALG getPasswordHashingAlg() {
return PASSWORD_HASHING_ALG.valueOf(password_hashing_alg.toUpperCase());
}
@TestOnly
public void setPasswordHashingAlg(PASSWORD_HASHING_ALG algo) {
this.password_hashing_alg = algo.toString();
}
public int getConfigVersion() {
return core_config_version;
}
public long getAccessTokenValidity() {
return access_token_validity;
}
public boolean getAccessTokenBlacklisting() {
return access_token_blacklisting;
}
public long getRefreshTokenValidity() {
return (long) (refresh_token_validity);
}
public long getPasswordResetTokenLifetime() {
return password_reset_token_lifetime;
}
public long getEmailVerificationTokenLifetime() {
return email_verification_token_lifetime;
}
public int getPasswordlessMaxCodeInputAttempts() {
return passwordless_max_code_input_attempts;
}
public long getPasswordlessCodeLifetime() {
return passwordless_code_lifetime;
}
public int getTotpMaxAttempts() {
return totp_max_attempts;
}
/**
* TOTP rate limit cooldown time (in seconds)
*/
public int getTotpRateLimitCooldownTimeSec() {
return totp_rate_limit_cooldown_sec;
}
public boolean isTelemetryDisabled() {
return disable_telemetry;
}
public String getInfoLogPath(Main main) {
return info_log_path;
}
public String getErrorLogPath(Main main) {
return error_log_path;
}
public boolean getAccessTokenSigningKeyDynamic() {
return access_token_signing_key_dynamic;
}
public long getAccessTokenDynamicSigningKeyUpdateInterval() {
return (long) (access_token_dynamic_signing_key_update_interval);
}
public String[] getAPIKeys() {
if (api_keys == null) {
return null;
}
return api_keys.trim().replaceAll("\\s", "").split(",");
}
public String getSuperTokensSaaSSecret() {
return supertokens_saas_secret;
}
public int getPort(Main main) {
return port;
}
public String getHost(Main main) {
return host;
}
public int getMaxThreadPoolSize() {
return max_server_pool_size;
}
public boolean getHttpsEnabled() {
return webserver_https_enabled;
}
private String getConfigFileLocation(Main main) {
return new File(CLIOptions.get(main).getConfigFilePath() == null
? CLIOptions.get(main).getInstallationPath() + "config.yaml"
: CLIOptions.get(main).getConfigFilePath()).getAbsolutePath();
}
void normalizeAndValidate(Main main, boolean includeConfigFilePath) throws InvalidConfigException {
if (isNormalizedAndValid) {
return;
}
// Validate
if (core_config_version == -1) {
throw new InvalidConfigException(
"'core_config_version' is not set in the config.yaml file. Please redownload and install "
+ "SuperTokens");
}
if (access_token_validity < 1 || access_token_validity > 86400000) {
throw new InvalidConfigException(
"'access_token_validity' must be between 1 and 86400000 seconds inclusive." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
Boolean validityTesting = CoreConfigTestContent.getInstance(main)
.getValue(CoreConfigTestContent.VALIDITY_TESTING);
validityTesting = validityTesting == null ? false : validityTesting;
if ((refresh_token_validity * 60) <= access_token_validity) {
if (!Main.isTesting || validityTesting) {
throw new InvalidConfigException(
"'refresh_token_validity' must be strictly greater than 'access_token_validity'." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
}
if (!Main.isTesting || validityTesting) { // since in testing we make this really small
if (access_token_dynamic_signing_key_update_interval < 1) {
throw new InvalidConfigException(
"'access_token_dynamic_signing_key_update_interval' must be greater than, equal to 1 hour." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
}
if (password_reset_token_lifetime <= 0) {
throw new InvalidConfigException("'password_reset_token_lifetime' must be >= 0");
}
if (email_verification_token_lifetime <= 0) {
throw new InvalidConfigException("'email_verification_token_lifetime' must be >= 0");
}
if (passwordless_code_lifetime <= 0) {
throw new InvalidConfigException("'passwordless_code_lifetime' must be > 0");
}
if (passwordless_max_code_input_attempts <= 0) {
throw new InvalidConfigException("'passwordless_max_code_input_attempts' must be > 0");
}
if (totp_max_attempts <= 0) {
throw new InvalidConfigException("'totp_max_attempts' must be > 0");
}
if (totp_rate_limit_cooldown_sec <= 0) {
throw new InvalidConfigException("'totp_rate_limit_cooldown_sec' must be > 0");
}
if (max_server_pool_size <= 0) {
throw new InvalidConfigException(
"'max_server_pool_size' must be >= 1." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
if (api_keys != null) {
String[] keys = api_keys.split(",");
for (int i = 0; i < keys.length; i++) {
String currKey = keys[i].trim();
if (currKey.length() < 20) {
throw new InvalidConfigException(
"One of the API keys is too short. Please use at least 20 characters");
}
for (int y = 0; y < currKey.length(); y++) {
char currChar = currKey.charAt(y);
if (!(currChar == '=' || currChar == '-' || (currChar >= '0' && currChar <= '9')
|| (currChar >= 'a' && currChar <= 'z') || (currChar >= 'A' && currChar <= 'Z'))) {
throw new InvalidConfigException(
"Invalid characters in API key. Please only use '=', '-' and alpha-numeric (including"
+ " capitals)");
}
}
}
}
if (supertokens_saas_secret != null) {
if (api_keys == null) {
throw new InvalidConfigException(
"supertokens_saas_secret can only be used when api_key is also defined");
}
if (supertokens_saas_secret.length() < 40) {
throw new InvalidConfigException(
"supertokens_saas_secret is too short. Please use at least 40 characters");
}
for (int y = 0; y < supertokens_saas_secret.length(); y++) {
char currChar = supertokens_saas_secret.charAt(y);
if (!(currChar == '=' || currChar == '-' || (currChar >= '0' && currChar <= '9')
|| (currChar >= 'a' && currChar <= 'z') || (currChar >= 'A' && currChar <= 'Z'))) {
throw new InvalidConfigException(
"Invalid characters in supertokens_saas_secret key. Please only use '=', '-' and " +
"alpha-numeric (including"
+ " capitals)");
}
}
}
if (!password_hashing_alg.equalsIgnoreCase("ARGON2") && !password_hashing_alg.equalsIgnoreCase("BCRYPT")) {
throw new InvalidConfigException("'password_hashing_alg' must be one of 'ARGON2' or 'BCRYPT'");
}
if (password_hashing_alg.equalsIgnoreCase("ARGON2")) {
if (argon2_iterations <= 0) {
throw new InvalidConfigException("'argon2_iterations' must be >= 1");
}
if (argon2_parallelism <= 0) {
throw new InvalidConfigException("'argon2_parallelism' must be >= 1");
}
if (argon2_memory_kb <= 0) {
throw new InvalidConfigException("'argon2_memory_kb' must be >= 1");
}
if (argon2_hashing_pool_size <= 0) {
throw new InvalidConfigException("'argon2_hashing_pool_size' must be >= 1");
}
if (argon2_hashing_pool_size > max_server_pool_size) {
throw new InvalidConfigException(
"'argon2_hashing_pool_size' must be <= 'max_server_pool_size'");
}
} else if (password_hashing_alg.equalsIgnoreCase("BCRYPT")) {
if (bcrypt_log_rounds <= 0) {
throw new InvalidConfigException("'bcrypt_log_rounds' must be >= 1");
}
}
if (base_path != null && !base_path.equals("") && !base_path.equals("/")) {
if (base_path.contains(" ")) {
throw new InvalidConfigException("Invalid characters in base_path config");
}
}
if (!log_level.equalsIgnoreCase("info") && !log_level.equalsIgnoreCase("none")
&& !log_level.equalsIgnoreCase("error") && !log_level.equalsIgnoreCase("warn")
&& !log_level.equalsIgnoreCase("debug")) {
throw new InvalidConfigException(
"'log_level' config must be one of \"NONE\",\"DEBUG\", \"INFO\", \"WARN\" or \"ERROR\".");
}
{
// IP Filter validation
RemoteAddrFilter filter = new RemoteAddrFilter();
if (ip_allow_regex != null) {
try {
filter.setAllow(ip_allow_regex);
} catch (PatternSyntaxException e) {
throw new InvalidConfigException("Provided regular expression is invalid for ip_allow_regex config");
}
}
if (ip_deny_regex != null) {
try {
filter.setDeny(ip_deny_regex);
} catch (PatternSyntaxException e) {
throw new InvalidConfigException("Provided regular expression is invalid for ip_deny_regex config");
}
}
}
if (supertokens_max_cdi_version != null) {
try {
SemVer version = new SemVer(supertokens_max_cdi_version);
if (!WebserverAPI.supportedVersions.contains(version)) {
throw new InvalidConfigException("supertokens_max_cdi_version is not a supported version");
}
} catch (IllegalArgumentException e) {
throw new InvalidConfigException("supertokens_max_cdi_version is not a valid semantic version");
}
}
// Normalize
if (ip_allow_regex != null) {
ip_allow_regex = ip_allow_regex.trim();
if (ip_allow_regex.equals("")) {
ip_allow_regex = null;
}
}
if (ip_deny_regex != null) {
ip_deny_regex = ip_deny_regex.trim();
if (ip_deny_regex.equals("")) {
ip_deny_regex = null;
}
}
if (log_level != null) {
log_level = log_level.trim().toUpperCase();
}
{ // info_log_path
if (info_log_path == null || info_log_path.equalsIgnoreCase("null")) {
info_log_path = "null";
} else {
if (info_log_path.equals(logDefault)) {
// this works for windows as well
info_log_path = CLIOptions.get(main).getInstallationPath() + "logs/info.log";
}
}
}
{ // error_log_path
if (error_log_path == null || error_log_path.equalsIgnoreCase("null")) {
error_log_path = "null";
} else {
if (error_log_path.equals(logDefault)) {
// this works for windows as well
error_log_path = CLIOptions.get(main).getInstallationPath() + "logs/error.log";
}
}
}
{ // base_path
String n_base_path = this.base_path; // Don't modify the original value from the config
if (n_base_path == null || n_base_path.equals("/") || n_base_path.isEmpty()) {
base_path = "";
} else {
while (n_base_path.contains("//")) { // Catch corner case where there are multiple '/' together
n_base_path = n_base_path.replace("//", "/");
}
if (!n_base_path.startsWith("/")) { // Add leading '/'
n_base_path = "/" + n_base_path;
}
if (n_base_path.endsWith("/")) { // Remove trailing '/'
n_base_path = n_base_path.substring(0, n_base_path.length() - 1);
}
base_path = n_base_path;
}
}
// the reason we do Math.max below is that if the password hashing algo is
// bcrypt,
// then we don't check the argon2 hashing pool size config at all. In this case,
// if the user gives a <= 0 number, it crashes the core (since it creates a
// blockedqueue in PaswordHashing
// .java with length <= 0). So we do a Math.max
argon2_hashing_pool_size = Math.max(1, argon2_hashing_pool_size);
firebase_password_hashing_pool_size = Math.max(1, firebase_password_hashing_pool_size);
if (api_keys != null) {
String[] apiKeys = api_keys.trim().replaceAll("\\s", "").split(",");
Arrays.sort(apiKeys);
api_keys = String.join(",", apiKeys);
}
if (supertokens_saas_secret != null) {
supertokens_saas_secret = supertokens_saas_secret.trim();
}
Integer cliPort = CLIOptions.get(main).getPort();
if (cliPort != null) {
port = cliPort;
}
String cliHost = CLIOptions.get(main).getHost();
if (cliHost != null) {
host = cliHost;
}
if (supertokens_saas_load_only_cud != null) {
try {
supertokens_saas_load_only_cud =
Utils.normalizeAndValidateConnectionUriDomain(supertokens_saas_load_only_cud, true);
} catch (ServletException e) {
throw new InvalidConfigException("supertokens_saas_load_only_cud is invalid");
}
}
access_token_validity = access_token_validity * 1000;
access_token_dynamic_signing_key_update_interval = access_token_dynamic_signing_key_update_interval * 3600 * 1000;
refresh_token_validity = refresh_token_validity * 60 * 1000;
isNormalizedAndValid = true;
}
public void createLoggingFile(Main main) throws IOException {
if (!getInfoLogPath(main).equals("null")) {
File infoLog = new File(getInfoLogPath(main));
if (!infoLog.exists()) {
File parent = infoLog.getParentFile();
if (parent != null) {
parent.mkdirs();
}
infoLog.createNewFile();
}
}
if (!getErrorLogPath(main).equals("null")) {
File errorLog = new File(getErrorLogPath(main));
if (!errorLog.exists()) {
File parent = errorLog.getParentFile();
if (parent != null) {
parent.mkdirs();
}
errorLog.createNewFile();
}
}
}
static void assertThatCertainConfigIsNotSetForAppOrTenants(JsonObject config) throws InvalidConfigException {
// these are all configs that are per core. So we do not allow the developer to set these dynamically.
for (Field field : CoreConfig.class.getDeclaredFields()) {
if (field.isAnnotationPresent(ConfigYamlOnly.class)) {
if (config.has(field.getName())) {
throw new InvalidConfigException(field.getName() + " can only be set via the core's base config setting");
}
}
}
}
void assertThatConfigFromSameAppIdAreNotConflicting(CoreConfig other) throws InvalidConfigException {
// we do not allow different values for this across tenants in the same app
for (Field field : CoreConfig.class.getDeclaredFields()) {
if (field.isAnnotationPresent(NotConflictingInApp.class)) {
try {
if (!Objects.equals(field.get(this), field.get(other))) {
throw new InvalidConfigException(
"You cannot set different values for " + field.getName() +
" for the same appId");
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
public String getMaxCDIVersion() {
return this.supertokens_max_cdi_version;
}
}
| supertokens/supertokens-core | src/main/java/io/supertokens/config/CoreConfig.java | 7,665 | // in seconds (Default 15 mins) | line_comment | nl | /*
* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* 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 io.supertokens.config;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.supertokens.Main;
import io.supertokens.cliOptions.CLIOptions;
import io.supertokens.config.annotations.ConfigYamlOnly;
import io.supertokens.config.annotations.IgnoreForAnnotationCheck;
import io.supertokens.config.annotations.NotConflictingInApp;
import io.supertokens.pluginInterface.LOG_LEVEL;
import io.supertokens.pluginInterface.exceptions.InvalidConfigException;
import io.supertokens.utils.SemVer;
import io.supertokens.webserver.Utils;
import io.supertokens.webserver.WebserverAPI;
import jakarta.servlet.ServletException;
import org.apache.catalina.filters.RemoteAddrFilter;
import org.jetbrains.annotations.TestOnly;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.PatternSyntaxException;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CoreConfig {
@IgnoreForAnnotationCheck
public static final String[] PROTECTED_CONFIGS = new String[]{
"ip_allow_regex",
"ip_deny_regex",
};
@IgnoreForAnnotationCheck
@JsonProperty
private int core_config_version = -1;
@NotConflictingInApp
@JsonProperty
private long access_token_validity = 3600; // in seconds
@NotConflictingInApp
@JsonProperty
private boolean access_token_blacklisting = false;
@NotConflictingInApp
@JsonProperty
private double refresh_token_validity = 60 * 2400; // in mins
@IgnoreForAnnotationCheck
@JsonProperty
private long password_reset_token_lifetime = 3600000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private long email_verification_token_lifetime = 24 * 3600 * 1000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private int passwordless_max_code_input_attempts = 5;
@IgnoreForAnnotationCheck
@JsonProperty
private long passwordless_code_lifetime = 900000; // in MS
@IgnoreForAnnotationCheck
@JsonProperty
private int totp_max_attempts = 5;
@IgnoreForAnnotationCheck
@JsonProperty
private int totp_rate_limit_cooldown_sec = 900; // in seconds<SUF>
@IgnoreForAnnotationCheck
private final String logDefault = "asdkfahbdfk3kjHS";
@ConfigYamlOnly
@JsonProperty
private String info_log_path = logDefault;
@ConfigYamlOnly
@JsonProperty
private String error_log_path = logDefault;
@NotConflictingInApp
@JsonProperty
private boolean access_token_signing_key_dynamic = true;
@NotConflictingInApp
@JsonProperty("access_token_dynamic_signing_key_update_interval")
@JsonAlias({"access_token_dynamic_signing_key_update_interval", "access_token_signing_key_update_interval"})
private double access_token_dynamic_signing_key_update_interval = 168; // in hours
@ConfigYamlOnly
@JsonProperty
private int port = 3567;
@ConfigYamlOnly
@JsonProperty
private String host = "localhost";
@ConfigYamlOnly
@JsonProperty
private int max_server_pool_size = 10;
@NotConflictingInApp
@JsonProperty
private String api_keys = null;
@NotConflictingInApp
@JsonProperty
private boolean disable_telemetry = false;
@NotConflictingInApp
@JsonProperty
private String password_hashing_alg = "BCRYPT";
@ConfigYamlOnly
@JsonProperty
private int argon2_iterations = 1;
@ConfigYamlOnly
@JsonProperty
private int argon2_memory_kb = 87795; // 85 mb
@ConfigYamlOnly
@JsonProperty
private int argon2_parallelism = 2;
@ConfigYamlOnly
@JsonProperty
private int argon2_hashing_pool_size = 1;
@ConfigYamlOnly
@JsonProperty
private int firebase_password_hashing_pool_size = 1;
@ConfigYamlOnly
@JsonProperty
private int bcrypt_log_rounds = 11;
// TODO: add https in later version
// # (OPTIONAL) boolean value (true or false). Set to true if you want to enable
// https requests to SuperTokens.
// # If you are not running SuperTokens within a closed network along with your
// API process, for
// # example if you are using multiple cloud vendors, then it is recommended to
// set this to true.
// # webserver_https_enabled:
@ConfigYamlOnly
@JsonProperty
private boolean webserver_https_enabled = false;
@ConfigYamlOnly
@JsonProperty
private String base_path = "";
@ConfigYamlOnly
@JsonProperty
private String log_level = "INFO";
@NotConflictingInApp
@JsonProperty
private String firebase_password_hashing_signer_key = null;
@IgnoreForAnnotationCheck
@JsonProperty
private String ip_allow_regex = null;
@IgnoreForAnnotationCheck
@JsonProperty
private String ip_deny_regex = null;
@ConfigYamlOnly
@JsonProperty
private String supertokens_saas_secret = null;
@NotConflictingInApp
@JsonProperty
private String supertokens_max_cdi_version = null;
@ConfigYamlOnly
@JsonProperty
private String supertokens_saas_load_only_cud = null;
@IgnoreForAnnotationCheck
private Set<LOG_LEVEL> allowedLogLevels = null;
@IgnoreForAnnotationCheck
private boolean isNormalizedAndValid = false;
public static Set<String> getValidFields() {
CoreConfig coreConfig = new CoreConfig();
JsonObject coreConfigObj = new GsonBuilder().serializeNulls().create().toJsonTree(coreConfig).getAsJsonObject();
Set<String> validFields = new HashSet<>();
for (Map.Entry<String, JsonElement> entry : coreConfigObj.entrySet()) {
validFields.add(entry.getKey());
}
// Adding the aliases
validFields.add("access_token_signing_key_update_interval");
return validFields;
}
public String getIpAllowRegex() {
return ip_allow_regex;
}
public String getIpDenyRegex() {
return ip_deny_regex;
}
public Set<LOG_LEVEL> getLogLevels(Main main) {
if (allowedLogLevels != null) {
return allowedLogLevels;
}
LOG_LEVEL logLevel = LOG_LEVEL.valueOf(this.log_level);
allowedLogLevels = new HashSet<>();
if (logLevel == LOG_LEVEL.NONE) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.ERROR);
if (logLevel == LOG_LEVEL.ERROR) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.WARN);
if (logLevel == LOG_LEVEL.WARN) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.INFO);
if (logLevel == LOG_LEVEL.INFO) {
return allowedLogLevels;
}
allowedLogLevels.add(LOG_LEVEL.DEBUG);
return allowedLogLevels;
}
public String getBasePath() {
return base_path;
}
public String getSuperTokensLoadOnlyCUD() {
return supertokens_saas_load_only_cud;
}
public enum PASSWORD_HASHING_ALG {
ARGON2, BCRYPT, FIREBASE_SCRYPT
}
public int getArgon2HashingPoolSize() {
return argon2_hashing_pool_size;
}
public int getFirebaseSCryptPasswordHashingPoolSize() {
return firebase_password_hashing_pool_size;
}
public int getArgon2Iterations() {
return argon2_iterations;
}
public int getBcryptLogRounds() {
return bcrypt_log_rounds;
}
public int getArgon2MemoryKb() {
return argon2_memory_kb;
}
public int getArgon2Parallelism() {
return argon2_parallelism;
}
public String getFirebase_password_hashing_signer_key() {
if (firebase_password_hashing_signer_key == null) {
throw new IllegalStateException("'firebase_password_hashing_signer_key' cannot be null");
}
return firebase_password_hashing_signer_key;
}
public PASSWORD_HASHING_ALG getPasswordHashingAlg() {
return PASSWORD_HASHING_ALG.valueOf(password_hashing_alg.toUpperCase());
}
@TestOnly
public void setPasswordHashingAlg(PASSWORD_HASHING_ALG algo) {
this.password_hashing_alg = algo.toString();
}
public int getConfigVersion() {
return core_config_version;
}
public long getAccessTokenValidity() {
return access_token_validity;
}
public boolean getAccessTokenBlacklisting() {
return access_token_blacklisting;
}
public long getRefreshTokenValidity() {
return (long) (refresh_token_validity);
}
public long getPasswordResetTokenLifetime() {
return password_reset_token_lifetime;
}
public long getEmailVerificationTokenLifetime() {
return email_verification_token_lifetime;
}
public int getPasswordlessMaxCodeInputAttempts() {
return passwordless_max_code_input_attempts;
}
public long getPasswordlessCodeLifetime() {
return passwordless_code_lifetime;
}
public int getTotpMaxAttempts() {
return totp_max_attempts;
}
/**
* TOTP rate limit cooldown time (in seconds)
*/
public int getTotpRateLimitCooldownTimeSec() {
return totp_rate_limit_cooldown_sec;
}
public boolean isTelemetryDisabled() {
return disable_telemetry;
}
public String getInfoLogPath(Main main) {
return info_log_path;
}
public String getErrorLogPath(Main main) {
return error_log_path;
}
public boolean getAccessTokenSigningKeyDynamic() {
return access_token_signing_key_dynamic;
}
public long getAccessTokenDynamicSigningKeyUpdateInterval() {
return (long) (access_token_dynamic_signing_key_update_interval);
}
public String[] getAPIKeys() {
if (api_keys == null) {
return null;
}
return api_keys.trim().replaceAll("\\s", "").split(",");
}
public String getSuperTokensSaaSSecret() {
return supertokens_saas_secret;
}
public int getPort(Main main) {
return port;
}
public String getHost(Main main) {
return host;
}
public int getMaxThreadPoolSize() {
return max_server_pool_size;
}
public boolean getHttpsEnabled() {
return webserver_https_enabled;
}
private String getConfigFileLocation(Main main) {
return new File(CLIOptions.get(main).getConfigFilePath() == null
? CLIOptions.get(main).getInstallationPath() + "config.yaml"
: CLIOptions.get(main).getConfigFilePath()).getAbsolutePath();
}
void normalizeAndValidate(Main main, boolean includeConfigFilePath) throws InvalidConfigException {
if (isNormalizedAndValid) {
return;
}
// Validate
if (core_config_version == -1) {
throw new InvalidConfigException(
"'core_config_version' is not set in the config.yaml file. Please redownload and install "
+ "SuperTokens");
}
if (access_token_validity < 1 || access_token_validity > 86400000) {
throw new InvalidConfigException(
"'access_token_validity' must be between 1 and 86400000 seconds inclusive." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
Boolean validityTesting = CoreConfigTestContent.getInstance(main)
.getValue(CoreConfigTestContent.VALIDITY_TESTING);
validityTesting = validityTesting == null ? false : validityTesting;
if ((refresh_token_validity * 60) <= access_token_validity) {
if (!Main.isTesting || validityTesting) {
throw new InvalidConfigException(
"'refresh_token_validity' must be strictly greater than 'access_token_validity'." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
}
if (!Main.isTesting || validityTesting) { // since in testing we make this really small
if (access_token_dynamic_signing_key_update_interval < 1) {
throw new InvalidConfigException(
"'access_token_dynamic_signing_key_update_interval' must be greater than, equal to 1 hour." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
}
if (password_reset_token_lifetime <= 0) {
throw new InvalidConfigException("'password_reset_token_lifetime' must be >= 0");
}
if (email_verification_token_lifetime <= 0) {
throw new InvalidConfigException("'email_verification_token_lifetime' must be >= 0");
}
if (passwordless_code_lifetime <= 0) {
throw new InvalidConfigException("'passwordless_code_lifetime' must be > 0");
}
if (passwordless_max_code_input_attempts <= 0) {
throw new InvalidConfigException("'passwordless_max_code_input_attempts' must be > 0");
}
if (totp_max_attempts <= 0) {
throw new InvalidConfigException("'totp_max_attempts' must be > 0");
}
if (totp_rate_limit_cooldown_sec <= 0) {
throw new InvalidConfigException("'totp_rate_limit_cooldown_sec' must be > 0");
}
if (max_server_pool_size <= 0) {
throw new InvalidConfigException(
"'max_server_pool_size' must be >= 1." +
(includeConfigFilePath ? " The config file can be"
+ " found here: " + getConfigFileLocation(main) : ""));
}
if (api_keys != null) {
String[] keys = api_keys.split(",");
for (int i = 0; i < keys.length; i++) {
String currKey = keys[i].trim();
if (currKey.length() < 20) {
throw new InvalidConfigException(
"One of the API keys is too short. Please use at least 20 characters");
}
for (int y = 0; y < currKey.length(); y++) {
char currChar = currKey.charAt(y);
if (!(currChar == '=' || currChar == '-' || (currChar >= '0' && currChar <= '9')
|| (currChar >= 'a' && currChar <= 'z') || (currChar >= 'A' && currChar <= 'Z'))) {
throw new InvalidConfigException(
"Invalid characters in API key. Please only use '=', '-' and alpha-numeric (including"
+ " capitals)");
}
}
}
}
if (supertokens_saas_secret != null) {
if (api_keys == null) {
throw new InvalidConfigException(
"supertokens_saas_secret can only be used when api_key is also defined");
}
if (supertokens_saas_secret.length() < 40) {
throw new InvalidConfigException(
"supertokens_saas_secret is too short. Please use at least 40 characters");
}
for (int y = 0; y < supertokens_saas_secret.length(); y++) {
char currChar = supertokens_saas_secret.charAt(y);
if (!(currChar == '=' || currChar == '-' || (currChar >= '0' && currChar <= '9')
|| (currChar >= 'a' && currChar <= 'z') || (currChar >= 'A' && currChar <= 'Z'))) {
throw new InvalidConfigException(
"Invalid characters in supertokens_saas_secret key. Please only use '=', '-' and " +
"alpha-numeric (including"
+ " capitals)");
}
}
}
if (!password_hashing_alg.equalsIgnoreCase("ARGON2") && !password_hashing_alg.equalsIgnoreCase("BCRYPT")) {
throw new InvalidConfigException("'password_hashing_alg' must be one of 'ARGON2' or 'BCRYPT'");
}
if (password_hashing_alg.equalsIgnoreCase("ARGON2")) {
if (argon2_iterations <= 0) {
throw new InvalidConfigException("'argon2_iterations' must be >= 1");
}
if (argon2_parallelism <= 0) {
throw new InvalidConfigException("'argon2_parallelism' must be >= 1");
}
if (argon2_memory_kb <= 0) {
throw new InvalidConfigException("'argon2_memory_kb' must be >= 1");
}
if (argon2_hashing_pool_size <= 0) {
throw new InvalidConfigException("'argon2_hashing_pool_size' must be >= 1");
}
if (argon2_hashing_pool_size > max_server_pool_size) {
throw new InvalidConfigException(
"'argon2_hashing_pool_size' must be <= 'max_server_pool_size'");
}
} else if (password_hashing_alg.equalsIgnoreCase("BCRYPT")) {
if (bcrypt_log_rounds <= 0) {
throw new InvalidConfigException("'bcrypt_log_rounds' must be >= 1");
}
}
if (base_path != null && !base_path.equals("") && !base_path.equals("/")) {
if (base_path.contains(" ")) {
throw new InvalidConfigException("Invalid characters in base_path config");
}
}
if (!log_level.equalsIgnoreCase("info") && !log_level.equalsIgnoreCase("none")
&& !log_level.equalsIgnoreCase("error") && !log_level.equalsIgnoreCase("warn")
&& !log_level.equalsIgnoreCase("debug")) {
throw new InvalidConfigException(
"'log_level' config must be one of \"NONE\",\"DEBUG\", \"INFO\", \"WARN\" or \"ERROR\".");
}
{
// IP Filter validation
RemoteAddrFilter filter = new RemoteAddrFilter();
if (ip_allow_regex != null) {
try {
filter.setAllow(ip_allow_regex);
} catch (PatternSyntaxException e) {
throw new InvalidConfigException("Provided regular expression is invalid for ip_allow_regex config");
}
}
if (ip_deny_regex != null) {
try {
filter.setDeny(ip_deny_regex);
} catch (PatternSyntaxException e) {
throw new InvalidConfigException("Provided regular expression is invalid for ip_deny_regex config");
}
}
}
if (supertokens_max_cdi_version != null) {
try {
SemVer version = new SemVer(supertokens_max_cdi_version);
if (!WebserverAPI.supportedVersions.contains(version)) {
throw new InvalidConfigException("supertokens_max_cdi_version is not a supported version");
}
} catch (IllegalArgumentException e) {
throw new InvalidConfigException("supertokens_max_cdi_version is not a valid semantic version");
}
}
// Normalize
if (ip_allow_regex != null) {
ip_allow_regex = ip_allow_regex.trim();
if (ip_allow_regex.equals("")) {
ip_allow_regex = null;
}
}
if (ip_deny_regex != null) {
ip_deny_regex = ip_deny_regex.trim();
if (ip_deny_regex.equals("")) {
ip_deny_regex = null;
}
}
if (log_level != null) {
log_level = log_level.trim().toUpperCase();
}
{ // info_log_path
if (info_log_path == null || info_log_path.equalsIgnoreCase("null")) {
info_log_path = "null";
} else {
if (info_log_path.equals(logDefault)) {
// this works for windows as well
info_log_path = CLIOptions.get(main).getInstallationPath() + "logs/info.log";
}
}
}
{ // error_log_path
if (error_log_path == null || error_log_path.equalsIgnoreCase("null")) {
error_log_path = "null";
} else {
if (error_log_path.equals(logDefault)) {
// this works for windows as well
error_log_path = CLIOptions.get(main).getInstallationPath() + "logs/error.log";
}
}
}
{ // base_path
String n_base_path = this.base_path; // Don't modify the original value from the config
if (n_base_path == null || n_base_path.equals("/") || n_base_path.isEmpty()) {
base_path = "";
} else {
while (n_base_path.contains("//")) { // Catch corner case where there are multiple '/' together
n_base_path = n_base_path.replace("//", "/");
}
if (!n_base_path.startsWith("/")) { // Add leading '/'
n_base_path = "/" + n_base_path;
}
if (n_base_path.endsWith("/")) { // Remove trailing '/'
n_base_path = n_base_path.substring(0, n_base_path.length() - 1);
}
base_path = n_base_path;
}
}
// the reason we do Math.max below is that if the password hashing algo is
// bcrypt,
// then we don't check the argon2 hashing pool size config at all. In this case,
// if the user gives a <= 0 number, it crashes the core (since it creates a
// blockedqueue in PaswordHashing
// .java with length <= 0). So we do a Math.max
argon2_hashing_pool_size = Math.max(1, argon2_hashing_pool_size);
firebase_password_hashing_pool_size = Math.max(1, firebase_password_hashing_pool_size);
if (api_keys != null) {
String[] apiKeys = api_keys.trim().replaceAll("\\s", "").split(",");
Arrays.sort(apiKeys);
api_keys = String.join(",", apiKeys);
}
if (supertokens_saas_secret != null) {
supertokens_saas_secret = supertokens_saas_secret.trim();
}
Integer cliPort = CLIOptions.get(main).getPort();
if (cliPort != null) {
port = cliPort;
}
String cliHost = CLIOptions.get(main).getHost();
if (cliHost != null) {
host = cliHost;
}
if (supertokens_saas_load_only_cud != null) {
try {
supertokens_saas_load_only_cud =
Utils.normalizeAndValidateConnectionUriDomain(supertokens_saas_load_only_cud, true);
} catch (ServletException e) {
throw new InvalidConfigException("supertokens_saas_load_only_cud is invalid");
}
}
access_token_validity = access_token_validity * 1000;
access_token_dynamic_signing_key_update_interval = access_token_dynamic_signing_key_update_interval * 3600 * 1000;
refresh_token_validity = refresh_token_validity * 60 * 1000;
isNormalizedAndValid = true;
}
public void createLoggingFile(Main main) throws IOException {
if (!getInfoLogPath(main).equals("null")) {
File infoLog = new File(getInfoLogPath(main));
if (!infoLog.exists()) {
File parent = infoLog.getParentFile();
if (parent != null) {
parent.mkdirs();
}
infoLog.createNewFile();
}
}
if (!getErrorLogPath(main).equals("null")) {
File errorLog = new File(getErrorLogPath(main));
if (!errorLog.exists()) {
File parent = errorLog.getParentFile();
if (parent != null) {
parent.mkdirs();
}
errorLog.createNewFile();
}
}
}
static void assertThatCertainConfigIsNotSetForAppOrTenants(JsonObject config) throws InvalidConfigException {
// these are all configs that are per core. So we do not allow the developer to set these dynamically.
for (Field field : CoreConfig.class.getDeclaredFields()) {
if (field.isAnnotationPresent(ConfigYamlOnly.class)) {
if (config.has(field.getName())) {
throw new InvalidConfigException(field.getName() + " can only be set via the core's base config setting");
}
}
}
}
void assertThatConfigFromSameAppIdAreNotConflicting(CoreConfig other) throws InvalidConfigException {
// we do not allow different values for this across tenants in the same app
for (Field field : CoreConfig.class.getDeclaredFields()) {
if (field.isAnnotationPresent(NotConflictingInApp.class)) {
try {
if (!Objects.equals(field.get(this), field.get(other))) {
throw new InvalidConfigException(
"You cannot set different values for " + field.getName() +
" for the same appId");
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
public String getMaxCDIVersion() {
return this.supertokens_max_cdi_version;
}
}
|
64287_4 | package com.superzanti.serversync.util.minecraft.config;
import java.io.IOException;
import java.util.HashMap;
/**
* Begone from here, there be beasts lurking.
*
* This will be removed entirely once the JSON config has had time to settle.
*/
public class FriendlyConfig extends HashMap<String, FriendlyConfigCategory> {
private static final long serialVersionUID = -8812919144959413432L;
// public void writeConfig(FriendlyConfigWriter writer) {
// this.forEach((key, category) -> {
//
// try {
// writer.writeOpenCategory(category.getCategoryName());
// for (int i = 0; i < category.size(); i++) {
// FriendlyConfigElement e = category.get(i);
// writer.writeElement(e);
// if (i == category.size() - 1) {
// // Last element
// writer.newLine();
// } else {
// writer.newLines(2);
// }
// }
// writer.writeCloseCategory();
// } catch (Exception e) {
// e.printStackTrace();
// }
// });
// try {
// writer.close();
// } catch (Exception e1) {
// e1.printStackTrace();
// }
// }
public void readConfig(FriendlyConfigReader read) {
FriendlyConfigElement entry;
try {
this.clear();
while ((entry = read.readNextElement()) != null) {
if (this.containsKey(entry.getCategoryName())) {
this.get(entry.getCategoryName()).add(entry);
} else {
FriendlyConfigCategory newCat = new FriendlyConfigCategory(entry.getCategoryName());
newCat.add(entry);
this.put(entry.getCategoryName(), newCat);
}
}
} catch (IOException e) {
// TODO handle these errors
e.printStackTrace();
}
try {
read.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public FriendlyConfigElement getEntryByName(String name) {
for (FriendlyConfigCategory cat : this.values()) {
for (FriendlyConfigElement e : cat) {
if (e.getName().equals(name)) {
return e;
}
}
}
return null;
}
}
| superzanti/ServerSync | src/main/java/com/superzanti/serversync/util/minecraft/config/FriendlyConfig.java | 655 | // FriendlyConfigElement e = category.get(i); | line_comment | nl | package com.superzanti.serversync.util.minecraft.config;
import java.io.IOException;
import java.util.HashMap;
/**
* Begone from here, there be beasts lurking.
*
* This will be removed entirely once the JSON config has had time to settle.
*/
public class FriendlyConfig extends HashMap<String, FriendlyConfigCategory> {
private static final long serialVersionUID = -8812919144959413432L;
// public void writeConfig(FriendlyConfigWriter writer) {
// this.forEach((key, category) -> {
//
// try {
// writer.writeOpenCategory(category.getCategoryName());
// for (int i = 0; i < category.size(); i++) {
// FriendlyConfigElement e<SUF>
// writer.writeElement(e);
// if (i == category.size() - 1) {
// // Last element
// writer.newLine();
// } else {
// writer.newLines(2);
// }
// }
// writer.writeCloseCategory();
// } catch (Exception e) {
// e.printStackTrace();
// }
// });
// try {
// writer.close();
// } catch (Exception e1) {
// e1.printStackTrace();
// }
// }
public void readConfig(FriendlyConfigReader read) {
FriendlyConfigElement entry;
try {
this.clear();
while ((entry = read.readNextElement()) != null) {
if (this.containsKey(entry.getCategoryName())) {
this.get(entry.getCategoryName()).add(entry);
} else {
FriendlyConfigCategory newCat = new FriendlyConfigCategory(entry.getCategoryName());
newCat.add(entry);
this.put(entry.getCategoryName(), newCat);
}
}
} catch (IOException e) {
// TODO handle these errors
e.printStackTrace();
}
try {
read.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public FriendlyConfigElement getEntryByName(String name) {
for (FriendlyConfigCategory cat : this.values()) {
for (FriendlyConfigElement e : cat) {
if (e.getName().equals(name)) {
return e;
}
}
}
return null;
}
}
|
151743_47 | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts verlaatsen
break;
default: //Player does not want to move -> nothing
}
}
}
}
| surdarmaputra/bomberman | BomberPlayer.java | 2,953 | //n->naar rechts verlaatsen | line_comment | nl | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts<SUF>
break;
default: //Player does not want to move -> nothing
}
}
}
}
|
83530_4 | package com.in28minutes.rest.webservices.restfulwebservices.helloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
// Controller
@RestController
public class HelloWorldController {
@Autowired
private MessageSource messageSource;
// GET
// URI - /hello-world
// method - "Hello World"
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// /hello-world-bean/path-variable/in28minutes
@GetMapping(path = "/hello-world-bean/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized(
// @RequestHeader(name = "Accept-Language", required = false) Locale locale
) {
return messageSource
.getMessage("good.morning.message", null, "Default message" //, locale);
, LocaleContextHolder.getLocale());
// return "Hello World";
// en = Hello World
// nl = Goedemorgen
// fr = Bonjour
}
}
| surdav/restful-web-services | src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloWorld/HelloWorldController.java | 432 | // en = Hello World | line_comment | nl | package com.in28minutes.rest.webservices.restfulwebservices.helloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
// Controller
@RestController
public class HelloWorldController {
@Autowired
private MessageSource messageSource;
// GET
// URI - /hello-world
// method - "Hello World"
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// /hello-world-bean/path-variable/in28minutes
@GetMapping(path = "/hello-world-bean/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized(
// @RequestHeader(name = "Accept-Language", required = false) Locale locale
) {
return messageSource
.getMessage("good.morning.message", null, "Default message" //, locale);
, LocaleContextHolder.getLocale());
// return "Hello World";
// en =<SUF>
// nl = Goedemorgen
// fr = Bonjour
}
}
|
37844_20 |
package demos.joinConvert;
/*
* Date: 11-12-1
*/
import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.EExpressionType;
import gudusoft.gsqlparser.ESqlStatementType;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.nodes.IExpressionVisitor;
import gudusoft.gsqlparser.nodes.TExpression;
import gudusoft.gsqlparser.nodes.TParseTreeNode;
import gudusoft.gsqlparser.nodes.TTable;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;
import java.util.ArrayList;
public class oracleJoinConverter
{
enum jointype {
inner, left, right
};
class FromClause
{
TTable joinTable;
String joinClause;
String condition;
}
class JoinCondition
{
public String lefttable, righttable, leftcolumn, rightcolumn;
public jointype jt;
public Boolean used;
public TExpression lexpr, rexpr, expr;
}
class getJoinConditionVisitor implements IExpressionVisitor
{
Boolean isFirstExpr = true;
ArrayList<JoinCondition> jrs = new ArrayList<JoinCondition>( );
public ArrayList<JoinCondition> getJrs( )
{
return jrs;
}
boolean is_compare_condition( EExpressionType t )
{
return ( ( t == EExpressionType.simple_comparison_t )
|| ( t == EExpressionType.group_comparison_t ) || ( t == EExpressionType.in_t ) );
}
private void analyzeJoinCondition( TExpression expr,
TExpression parent_expr )
{
TExpression slexpr, srexpr, lc_expr = expr;
if ( is_compare_condition( lc_expr.getExpressionType( ) ) )
{
slexpr = lc_expr.getLeftOperand( );
srexpr = lc_expr.getRightOperand( );
if ( slexpr.isOracleOuterJoin( ) || srexpr.isOracleOuterJoin( ) )
{
JoinCondition jr = new JoinCondition( );
jr.used = false;
jr.lexpr = slexpr;
jr.rexpr = srexpr;
jr.expr = expr;
if ( slexpr.isOracleOuterJoin( ) )
{
// If the plus is on the left, the join type is right
// out join.
jr.jt = jointype.right;
// remove (+)
slexpr.getEndToken( ).setString( "" );
}
if ( srexpr.isOracleOuterJoin( ) )
{
// If the plus is on the right, the join type is left
// out join.
jr.jt = jointype.left;
srexpr.getEndToken( ).setString( "" );
}
if ( ( slexpr.getExpressionType( ) == EExpressionType.simple_constant_t ) )
{
jr.lefttable = null;
jr.righttable = getExpressionTable( srexpr );
}
else if ( srexpr.getExpressionType( ) == EExpressionType.simple_constant_t )
{
jr.righttable = null;
jr.lefttable = getExpressionTable( slexpr );
}
else
{
jr.lefttable = getExpressionTable( slexpr );
jr.righttable = getExpressionTable( srexpr );
}
jrs.add( jr );
// System.out.printf( "join condition: %s\n", expr.toString(
// ) );
}
else if ( ( slexpr.getExpressionType( ) == EExpressionType.simple_object_name_t )
&& ( !slexpr.toString( ).startsWith( ":" ) )
&& ( !slexpr.toString( ).startsWith( "?" ) )
&& ( srexpr.getExpressionType( ) == EExpressionType.simple_object_name_t )
&& ( !srexpr.toString( ).startsWith( ":" ) )
&& ( !srexpr.toString( ).startsWith( "?" ) ) )
{
JoinCondition jr = new JoinCondition( );
jr.used = false;
jr.lexpr = slexpr;
jr.rexpr = srexpr;
jr.expr = expr;
jr.jt = jointype.inner;
jr.lefttable = getExpressionTable( slexpr );
jr.righttable = getExpressionTable( srexpr );
jrs.add( jr );
// System.out.printf(
// "join condition: %s, %s:%d, %s:%d, %s\n",
// expr.toString( ),
// slexpr.toString( ),
// slexpr.getExpressionType( ),
// srexpr.toString( ),
// srexpr.getExpressionType( ),
// srexpr.getObjectOperand( ).getObjectType( ) );
}
else
{
// not a join condition
}
}
}
public boolean exprVisit( TParseTreeNode pNode, boolean isLeafNode )
{
TExpression expr = (TExpression) pNode;
// System.out.printf("expr visited: %s\n",expr.toString());
analyzeJoinCondition( expr, expr );
return true;
}
}
private String ErrorMessage = "";
public String getErrorMessage( )
{
return ErrorMessage;
}
private int ErrorNo;
private String query;
public oracleJoinConverter( String sql )
{
this.query = sql;
}
public String getQuery( )
{
// remove blank line from query
return this.query.replaceAll( "(?m)^[ \t]*\r?\n", "" );
}
public int convert( )
{
TGSqlParser sqlparser = new TGSqlParser( EDbVendor.dbvoracle );
sqlparser.sqltext = this.query;
ErrorNo = sqlparser.parse( );
if ( ErrorNo != 0 )
{
ErrorMessage = sqlparser.getErrormessage( );
return ErrorNo;
}
if ( sqlparser.sqlstatements.get( 0 ).sqlstatementtype != ESqlStatementType.sstselect )
return 0;
TSelectSqlStatement select = (TSelectSqlStatement) sqlparser.sqlstatements.get( 0 );
analyzeSelect( select );
this.query = select.toString( );
return ErrorNo;
}
private boolean isNameOfTable( TTable table, String name )
{
return ( name == null ) ? false : table.getName( )
.equalsIgnoreCase( name );
}
private boolean isAliasOfTable( TTable table, String alias )
{
if ( table.getAliasClause( ) == null )
{
return false;
}
else
return ( alias == null ) ? false : table.getAliasClause( )
.toString( )
.equalsIgnoreCase( alias );
}
private boolean isNameOrAliasOfTable( TTable table, String str )
{
return isAliasOfTable( table, str ) || isNameOfTable( table, str );
}
private boolean areTableJoined( TTable lefttable, TTable righttable,
ArrayList<JoinCondition> jrs )
{
boolean ret = false;
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( jc.used )
{
continue;
}
ret = isNameOrAliasOfTable( lefttable, jc.lefttable )
&& isNameOrAliasOfTable( righttable, jc.righttable );
if ( ret )
break;
ret = isNameOrAliasOfTable( lefttable, jc.righttable )
&& isNameOrAliasOfTable( righttable, jc.lefttable );
if ( ret )
break;
}
return ret;
}
private String getJoinType( ArrayList<JoinCondition> jrs )
{
String str = "inner join";
for ( int i = 0; i < jrs.size( ); i++ )
{
if ( jrs.get( i ).jt == jointype.left )
{
str = "left outer join";
break;
}
else if ( jrs.get( i ).jt == jointype.right )
{
str = "right outer join";
break;
}
}
return str;
}
private ArrayList<JoinCondition> getJoinCondition( TTable lefttable,
TTable righttable, ArrayList<JoinCondition> jrs )
{
ArrayList<JoinCondition> lcjrs = new ArrayList<JoinCondition>( );
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( jc.used )
{
continue;
}
if ( isNameOrAliasOfTable( lefttable, jc.lefttable )
&& isNameOrAliasOfTable( righttable, jc.righttable ) )
{
lcjrs.add( jc );
jc.used = true;
}
else if ( isNameOrAliasOfTable( lefttable, jc.righttable )
&& isNameOrAliasOfTable( righttable, jc.lefttable ) )
{
lcjrs.add( jc );
jc.used = true;
}
else if ( ( jc.lefttable == null )
&& ( isNameOrAliasOfTable( lefttable, jc.righttable ) || isNameOrAliasOfTable( righttable,
jc.righttable ) ) )
{
// 'Y' = righttable.c1(+)
lcjrs.add( jc );
jc.used = true;
}
else if ( ( jc.righttable == null )
&& ( isNameOrAliasOfTable( lefttable, jc.lefttable ) || isNameOrAliasOfTable( righttable,
jc.lefttable ) ) )
{
// lefttable.c1(+) = 'Y'
lcjrs.add( jc );
jc.used = true;
}
}
return lcjrs;
}
private void analyzeSelect( TSelectSqlStatement select )
{
if ( !select.isCombinedQuery( ) )
{
if ( select.tables.size( ) == 1 )
return;
if ( select.getWhereClause( ) == null )
{
if ( select.tables.size( ) > 1 )
{
// cross join
String str = select.tables.getTable( 0 )
.getFullNameWithAliasString( );
for ( int i = 1; i < select.tables.size( ); i++ )
{
str = str
+ "\ncross join "
+ select.tables.getTable( i )
.getFullNameWithAliasString( );
}
for ( int k = select.joins.size( ) - 1; k > 0; k-- )
{
select.joins.removeJoin( k );
}
select.joins.getJoin( 0 ).setString( str );
}
}
else
{
getJoinConditionVisitor v = new getJoinConditionVisitor( );
// get join conditions
select.getWhereClause( ).getCondition( ).preOrderTraverse( v );
ArrayList<JoinCondition> jrs = v.getJrs( );
// Console.WriteLine(jrs.Count);
boolean tableUsed[] = new boolean[select.tables.size( )];
for ( int i = 0; i < select.tables.size( ); i++ )
{
tableUsed[i] = false;
}
// make first table to be the left most joined table
String fromclause = select.tables.getTable( 0 )
.getFullNameWithAliasString( );
tableUsed[0] = true;
boolean foundTableJoined;
ArrayList<FromClause> fromClauses = new ArrayList<FromClause>( );
for ( ;; )
{
foundTableJoined = false;
for ( int i = 0; i < select.tables.size( ); i++ )
{
TTable lcTable1 = select.tables.getTable( i );
TTable leftTable = null, rightTable = null;
for ( int j = i + 1; j < select.tables.size( ); j++ )
{
TTable lcTable2 = select.tables.getTable( j );
if ( areTableJoined( lcTable1, lcTable2, jrs ) )
{
if ( tableUsed[i] && ( !tableUsed[j] ) )
{
leftTable = lcTable1;
rightTable = lcTable2;
}
else if ( ( !tableUsed[i] ) && tableUsed[j] )
{
leftTable = lcTable2;
rightTable = lcTable1;
}
if ( ( leftTable != null )
&& ( rightTable != null ) )
{
ArrayList<JoinCondition> lcjrs = getJoinCondition( leftTable,
rightTable,
jrs );
FromClause fc = new FromClause( );
fc.joinTable = rightTable;
fc.joinClause = getJoinType( lcjrs );
String condition = "";
for ( int k = 0; k < lcjrs.size( ); k++ )
{
condition += lcjrs.get( k ).expr.toString( );
if ( k != lcjrs.size( ) - 1 )
{
condition += " and ";
}
TExpression lc_expr = lcjrs.get( k ).expr;
lc_expr.remove( );
}
fc.condition = condition;
fromClauses.add( fc );
tableUsed[i] = true;
tableUsed[j] = true;
foundTableJoined = true;
}
}
}
}
if ( !foundTableJoined )
{
break;
}
}
// are all join conditions used?
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( !jc.used )
{
for ( int j = fromClauses.size( ) - 1; j >= 0; j-- )
{
if ( isNameOrAliasOfTable( fromClauses.get( j ).joinTable,
jc.lefttable )
|| isNameOrAliasOfTable( fromClauses.get( j ).joinTable,
jc.righttable ) )
{
fromClauses.get( j ).condition += " and "
+ jc.expr.toString( );
jc.used = true;
jc.expr.remove( );
break;
}
}
}
}
for ( int i = 0; i < select.tables.size( ); i++ )
{
if ( !tableUsed[i] )
{
ErrorNo++;
ErrorMessage += String.format( "%sError %d, Message: %s",
System.getProperty( "line.separator" ),
ErrorNo,
"This table has no join condition: "
+ select.tables.getTable( i )
.getFullName( ) );
}
}
// link all join clause
for ( int i = 0; i < fromClauses.size( ); i++ )
{
FromClause fc = fromClauses.get( i );
// fromclause += System.getProperty("line.separator") +
// fc.joinClause
// +" "+fc.joinTable.getFullNameWithAliasString()+" on "+fc.condition;
fromclause += "\n"
+ fc.joinClause
+ " "
+ fc.joinTable.getFullNameWithAliasString( )
+ " on "
+ fc.condition;
}
for ( int k = select.joins.size( ) - 1; k > 0; k-- )
{
select.joins.removeJoin( k );
}
select.joins.getJoin( 0 ).setString( fromclause );
if ( ( select.getWhereClause( ).getCondition( ).getStartToken( ) == null )
|| ( select.getWhereClause( )
.getCondition( )
.toString( )
.trim( )
.length( ) == 0 ) )
{
// no where condition, remove WHERE keyword
select.getWhereClause( ).setString( " " );
}
}
}
else
{
analyzeSelect( select.getLeftStmt( ) );
analyzeSelect( select.getRightStmt( ) );
}
}
private String getExpressionTable( TExpression expr )
{
if ( expr.getObjectOperand( ) != null )
return expr.getObjectOperand( ).getObjectString( );
else if ( expr.getLeftOperand( ) != null
&& expr.getLeftOperand( ).getObjectOperand( ) != null )
return expr.getLeftOperand( ).getObjectOperand( ).getObjectString( );
else if ( expr.getRightOperand( ) != null
&& expr.getRightOperand( ).getObjectOperand( ) != null )
return expr.getRightOperand( )
.getObjectOperand( )
.getObjectString( );
else
return null;
}
public static void main( String args[] )
{
// String sqltext = "SELECT e.employee_id,\n" +
// " e.last_name,\n" +
// " e.department_id\n" +
// "FROM employees e,\n" +
// " departments d\n" ;
String sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id = d.department_id";
sqltext = "SELECT m.*, \n"
+ " altname.last_name last_name_student, \n"
+ " altname.first_name first_name_student, \n"
+ " ccu.date_joined, \n"
+ " ccu.last_login, \n"
+ " ccu.photo_id, \n"
+ " ccu.last_updated \n"
+ "FROM summit.mstr m, \n"
+ " summit.alt_name altname, \n"
+ " smmtccon.ccn_user ccu \n"
+ "WHERE m.id =?\n"
+ " AND m.id = altname.id(+) \n"
+ " AND m.id = ccu.id(+) \n"
+ " AND altname.grad_name_ind(+) = '*'";
// sqltext = "SELECT * \n" +
// "FROM summit.mstr m, \n" +
// " summit.alt_name altname, \n" +
// " smmtccon.ccn_user ccu \n" +
// //" uhelp.deg_coll deg \n" +
// "WHERE m.id = ? \n" +
// " AND m.id = altname.id(+) \n" +
// " AND m.id = ccu.id(+) \n" +
// " AND 'N' = ccu.admin(+) \n" +
// " AND altname.grad_name_ind(+) = '*'";
// sqltext = "SELECT ppp.project_name proj_name, \n" +
// " pr.role_title user_role \n" +
// "FROM jboss_admin.portal_application_location pal, \n" +
// " jboss_admin.portal_application pa, \n" +
// " jboss_admin.portal_user_app_location_role pualr, \n" +
// " jboss_admin.portal_location pl, \n" +
// " jboss_admin.portal_role pr, \n" +
// " jboss_admin.portal_pep_project ppp, \n" +
// " jboss_admin.portal_user pu \n" +
// "WHERE (pal.application_location_id = pualr.application_location_id \n"
// +
// " AND pu.jbp_uid = pualr.jbp_uid \n" +
// " AND pu.username = 'USERID') \n" +
// " AND pal.uidr_uid = pl.uidr_uid \n" +
// " AND pal.application_id = pa.application_id \n" +
// " AND pal.application_id = pr.application_id \n" +
// " AND pualr.role_id = pr.role_id \n" +
// " AND pualr.project_id = ppp.project_id \n" +
// " AND pa.application_id = 'APPID' ";
sqltext = "SELECT * \n"
+ "FROM smmtccon.ccn_menu menu, \n"
+ " smmtccon.ccn_page paget \n"
+ "WHERE ( menu.page_id = paget.page_id(+) ) \n"
+ " AND ( NOT enabled = 'N' ) \n"
+ " AND ( ( :parent_menu_id IS NULL \n"
+ " AND menu.parent_menu_id IS NULL ) \n"
+ " OR ( menu.parent_menu_id = :parent_menu_id ) ) \n"
+ "ORDER BY item_seq;";
sqltext = "select *\n"
+ "from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
+ " , ods_stg_pnb_stuf_pers_adr pas\n"
+ " , ods_stg_pnb_stuf_pers_nat nat\n"
+ " , ods_stg_pnb_stuf_adr adr\n"
+ " , ods_stg_pnb_stuf_np prs\n"
+ "where \n"
+ " pas.soort_adres = lst.soort_adres\n"
+ " and prs.id = nat.prs_id(+)\n"
+ " and adr.id = pas.adr_id\n"
+ " and prs.id = pas.prs_id\n"
+ " and lst.persoonssoort = 'PERSOON'\n"
+ " and pas.einddatumrelatie is null ";
sqltext = "select *\n"
+ " from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
+ " , ods_stg_pnb_stuf_np prs\n"
+ " , ods_stg_pnb_stuf_pers_adr pas\n"
+ " , ods_stg_pnb_stuf_pers_nat nat\n"
+ " , ods_stg_pnb_stuf_adr adr\n"
+ " where \n"
+ " pas.soort_adres = lst.soort_adres\n"
+ " and prs.id(+) = nat.prs_id\n"
+ " and adr.id = pas.adr_id\n"
+ " and prs.id = pas.prs_id\n"
+ " and lst.persoonssoort = 'PERSOON'\n"
+ " and pas.einddatumrelatie is null";
// sqltext = "SELECT ppp.project_name proj_name, \n"
// + " pr.role_title user_role \n"
// + "FROM jboss_admin.portal_application_location pal, \n"
// + " jboss_admin.portal_application pa, \n"
// + " jboss_admin.portal_user_app_location_role pualr, \n"
// + " jboss_admin.portal_location pl, \n"
// + " jboss_admin.portal_role pr, \n"
// + " jboss_admin.portal_pep_project ppp, \n"
// + " jboss_admin.portal_user pu \n"
// +
// "WHERE (pal.application_location_id = pualr.application_location_id \n"
// + " AND pu.jbp_uid = pualr.jbp_uid \n"
// + " AND pu.username = 'USERID') \n"
// + " AND pal.uidr_uid = pl.uidr_uid \n"
// + " AND pal.application_id = pa.application_id \n"
// + " AND pal.application_id = pr.application_id \n"
// + " AND pualr.role_id = pr.role_id \n"
// + " AND pualr.project_id = ppp.project_id \n"
// + " AND pa.application_id = 'APPID'";
//
// sqltext = "select *\n"
// + "from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
// + " , ods_stg_pnb_stuf_np prs\n"
// + " , ods_stg_pnb_stuf_pers_adr pas\n"
// + " , ods_stg_pnb_stuf_pers_nat nat\n"
// + " , ods_stg_pnb_stuf_adr adr\n"
// + "where \n"
// + " pas.soort_adres = lst.soort_adres\n"
// + " and prs.id = nat.prs_id(+)\n"
// + " and adr.id = pas.adr_id\n"
// + " and prs.id = pas.prs_id\n"
// + " and lst.persoonssoort = 'PERSOON'\n"
// + " and pas.einddatumrelatie is null";
// sqltext = "select *\n"
// + "from ods_trf_pnb_stuf_lijst_adrsrt2 lst,\n"
// + " ods_stg_pnb_stuf_np prs,\n"
// + " ods_stg_pnb_stuf_pers_adr pas,\n"
// + " ods_stg_pnb_stuf_pers_nat nat,\n"
// + " ods_stg_pnb_stuf_adr adr\n"
// + "where pas.soort_adres = lst.soort_adres\n"
// + " and prs.id(+) = nat.prs_id\n"
// + " and adr.id = pas.adr_id\n"
// + " and prs.id = pas.prs_id\n"
// + " and lst.persoonssoort = 'PERSOON'\n"
// + " and pas.einddatumrelatie is null\n";
sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id = d.department_id(+)";
sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id(+) = d.department_id";
System.out.println( "SQL with Oracle propriety joins" );
System.out.println( sqltext );
oracleJoinConverter converter = new oracleJoinConverter( sqltext );
if ( converter.convert( ) != 0 )
{
System.out.println( converter.getErrorMessage( ) );
}
else
{
System.out.println( "\nSQL in ANSI joins" );
System.out.println( converter.getQuery( ) );
}
}
} | sushilshah/gsp-sqlparser | demos/joinConvert/oracleJoinConverter.java | 8,154 | // " e.department_id\n" + | line_comment | nl |
package demos.joinConvert;
/*
* Date: 11-12-1
*/
import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.EExpressionType;
import gudusoft.gsqlparser.ESqlStatementType;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.nodes.IExpressionVisitor;
import gudusoft.gsqlparser.nodes.TExpression;
import gudusoft.gsqlparser.nodes.TParseTreeNode;
import gudusoft.gsqlparser.nodes.TTable;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;
import java.util.ArrayList;
public class oracleJoinConverter
{
enum jointype {
inner, left, right
};
class FromClause
{
TTable joinTable;
String joinClause;
String condition;
}
class JoinCondition
{
public String lefttable, righttable, leftcolumn, rightcolumn;
public jointype jt;
public Boolean used;
public TExpression lexpr, rexpr, expr;
}
class getJoinConditionVisitor implements IExpressionVisitor
{
Boolean isFirstExpr = true;
ArrayList<JoinCondition> jrs = new ArrayList<JoinCondition>( );
public ArrayList<JoinCondition> getJrs( )
{
return jrs;
}
boolean is_compare_condition( EExpressionType t )
{
return ( ( t == EExpressionType.simple_comparison_t )
|| ( t == EExpressionType.group_comparison_t ) || ( t == EExpressionType.in_t ) );
}
private void analyzeJoinCondition( TExpression expr,
TExpression parent_expr )
{
TExpression slexpr, srexpr, lc_expr = expr;
if ( is_compare_condition( lc_expr.getExpressionType( ) ) )
{
slexpr = lc_expr.getLeftOperand( );
srexpr = lc_expr.getRightOperand( );
if ( slexpr.isOracleOuterJoin( ) || srexpr.isOracleOuterJoin( ) )
{
JoinCondition jr = new JoinCondition( );
jr.used = false;
jr.lexpr = slexpr;
jr.rexpr = srexpr;
jr.expr = expr;
if ( slexpr.isOracleOuterJoin( ) )
{
// If the plus is on the left, the join type is right
// out join.
jr.jt = jointype.right;
// remove (+)
slexpr.getEndToken( ).setString( "" );
}
if ( srexpr.isOracleOuterJoin( ) )
{
// If the plus is on the right, the join type is left
// out join.
jr.jt = jointype.left;
srexpr.getEndToken( ).setString( "" );
}
if ( ( slexpr.getExpressionType( ) == EExpressionType.simple_constant_t ) )
{
jr.lefttable = null;
jr.righttable = getExpressionTable( srexpr );
}
else if ( srexpr.getExpressionType( ) == EExpressionType.simple_constant_t )
{
jr.righttable = null;
jr.lefttable = getExpressionTable( slexpr );
}
else
{
jr.lefttable = getExpressionTable( slexpr );
jr.righttable = getExpressionTable( srexpr );
}
jrs.add( jr );
// System.out.printf( "join condition: %s\n", expr.toString(
// ) );
}
else if ( ( slexpr.getExpressionType( ) == EExpressionType.simple_object_name_t )
&& ( !slexpr.toString( ).startsWith( ":" ) )
&& ( !slexpr.toString( ).startsWith( "?" ) )
&& ( srexpr.getExpressionType( ) == EExpressionType.simple_object_name_t )
&& ( !srexpr.toString( ).startsWith( ":" ) )
&& ( !srexpr.toString( ).startsWith( "?" ) ) )
{
JoinCondition jr = new JoinCondition( );
jr.used = false;
jr.lexpr = slexpr;
jr.rexpr = srexpr;
jr.expr = expr;
jr.jt = jointype.inner;
jr.lefttable = getExpressionTable( slexpr );
jr.righttable = getExpressionTable( srexpr );
jrs.add( jr );
// System.out.printf(
// "join condition: %s, %s:%d, %s:%d, %s\n",
// expr.toString( ),
// slexpr.toString( ),
// slexpr.getExpressionType( ),
// srexpr.toString( ),
// srexpr.getExpressionType( ),
// srexpr.getObjectOperand( ).getObjectType( ) );
}
else
{
// not a join condition
}
}
}
public boolean exprVisit( TParseTreeNode pNode, boolean isLeafNode )
{
TExpression expr = (TExpression) pNode;
// System.out.printf("expr visited: %s\n",expr.toString());
analyzeJoinCondition( expr, expr );
return true;
}
}
private String ErrorMessage = "";
public String getErrorMessage( )
{
return ErrorMessage;
}
private int ErrorNo;
private String query;
public oracleJoinConverter( String sql )
{
this.query = sql;
}
public String getQuery( )
{
// remove blank line from query
return this.query.replaceAll( "(?m)^[ \t]*\r?\n", "" );
}
public int convert( )
{
TGSqlParser sqlparser = new TGSqlParser( EDbVendor.dbvoracle );
sqlparser.sqltext = this.query;
ErrorNo = sqlparser.parse( );
if ( ErrorNo != 0 )
{
ErrorMessage = sqlparser.getErrormessage( );
return ErrorNo;
}
if ( sqlparser.sqlstatements.get( 0 ).sqlstatementtype != ESqlStatementType.sstselect )
return 0;
TSelectSqlStatement select = (TSelectSqlStatement) sqlparser.sqlstatements.get( 0 );
analyzeSelect( select );
this.query = select.toString( );
return ErrorNo;
}
private boolean isNameOfTable( TTable table, String name )
{
return ( name == null ) ? false : table.getName( )
.equalsIgnoreCase( name );
}
private boolean isAliasOfTable( TTable table, String alias )
{
if ( table.getAliasClause( ) == null )
{
return false;
}
else
return ( alias == null ) ? false : table.getAliasClause( )
.toString( )
.equalsIgnoreCase( alias );
}
private boolean isNameOrAliasOfTable( TTable table, String str )
{
return isAliasOfTable( table, str ) || isNameOfTable( table, str );
}
private boolean areTableJoined( TTable lefttable, TTable righttable,
ArrayList<JoinCondition> jrs )
{
boolean ret = false;
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( jc.used )
{
continue;
}
ret = isNameOrAliasOfTable( lefttable, jc.lefttable )
&& isNameOrAliasOfTable( righttable, jc.righttable );
if ( ret )
break;
ret = isNameOrAliasOfTable( lefttable, jc.righttable )
&& isNameOrAliasOfTable( righttable, jc.lefttable );
if ( ret )
break;
}
return ret;
}
private String getJoinType( ArrayList<JoinCondition> jrs )
{
String str = "inner join";
for ( int i = 0; i < jrs.size( ); i++ )
{
if ( jrs.get( i ).jt == jointype.left )
{
str = "left outer join";
break;
}
else if ( jrs.get( i ).jt == jointype.right )
{
str = "right outer join";
break;
}
}
return str;
}
private ArrayList<JoinCondition> getJoinCondition( TTable lefttable,
TTable righttable, ArrayList<JoinCondition> jrs )
{
ArrayList<JoinCondition> lcjrs = new ArrayList<JoinCondition>( );
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( jc.used )
{
continue;
}
if ( isNameOrAliasOfTable( lefttable, jc.lefttable )
&& isNameOrAliasOfTable( righttable, jc.righttable ) )
{
lcjrs.add( jc );
jc.used = true;
}
else if ( isNameOrAliasOfTable( lefttable, jc.righttable )
&& isNameOrAliasOfTable( righttable, jc.lefttable ) )
{
lcjrs.add( jc );
jc.used = true;
}
else if ( ( jc.lefttable == null )
&& ( isNameOrAliasOfTable( lefttable, jc.righttable ) || isNameOrAliasOfTable( righttable,
jc.righttable ) ) )
{
// 'Y' = righttable.c1(+)
lcjrs.add( jc );
jc.used = true;
}
else if ( ( jc.righttable == null )
&& ( isNameOrAliasOfTable( lefttable, jc.lefttable ) || isNameOrAliasOfTable( righttable,
jc.lefttable ) ) )
{
// lefttable.c1(+) = 'Y'
lcjrs.add( jc );
jc.used = true;
}
}
return lcjrs;
}
private void analyzeSelect( TSelectSqlStatement select )
{
if ( !select.isCombinedQuery( ) )
{
if ( select.tables.size( ) == 1 )
return;
if ( select.getWhereClause( ) == null )
{
if ( select.tables.size( ) > 1 )
{
// cross join
String str = select.tables.getTable( 0 )
.getFullNameWithAliasString( );
for ( int i = 1; i < select.tables.size( ); i++ )
{
str = str
+ "\ncross join "
+ select.tables.getTable( i )
.getFullNameWithAliasString( );
}
for ( int k = select.joins.size( ) - 1; k > 0; k-- )
{
select.joins.removeJoin( k );
}
select.joins.getJoin( 0 ).setString( str );
}
}
else
{
getJoinConditionVisitor v = new getJoinConditionVisitor( );
// get join conditions
select.getWhereClause( ).getCondition( ).preOrderTraverse( v );
ArrayList<JoinCondition> jrs = v.getJrs( );
// Console.WriteLine(jrs.Count);
boolean tableUsed[] = new boolean[select.tables.size( )];
for ( int i = 0; i < select.tables.size( ); i++ )
{
tableUsed[i] = false;
}
// make first table to be the left most joined table
String fromclause = select.tables.getTable( 0 )
.getFullNameWithAliasString( );
tableUsed[0] = true;
boolean foundTableJoined;
ArrayList<FromClause> fromClauses = new ArrayList<FromClause>( );
for ( ;; )
{
foundTableJoined = false;
for ( int i = 0; i < select.tables.size( ); i++ )
{
TTable lcTable1 = select.tables.getTable( i );
TTable leftTable = null, rightTable = null;
for ( int j = i + 1; j < select.tables.size( ); j++ )
{
TTable lcTable2 = select.tables.getTable( j );
if ( areTableJoined( lcTable1, lcTable2, jrs ) )
{
if ( tableUsed[i] && ( !tableUsed[j] ) )
{
leftTable = lcTable1;
rightTable = lcTable2;
}
else if ( ( !tableUsed[i] ) && tableUsed[j] )
{
leftTable = lcTable2;
rightTable = lcTable1;
}
if ( ( leftTable != null )
&& ( rightTable != null ) )
{
ArrayList<JoinCondition> lcjrs = getJoinCondition( leftTable,
rightTable,
jrs );
FromClause fc = new FromClause( );
fc.joinTable = rightTable;
fc.joinClause = getJoinType( lcjrs );
String condition = "";
for ( int k = 0; k < lcjrs.size( ); k++ )
{
condition += lcjrs.get( k ).expr.toString( );
if ( k != lcjrs.size( ) - 1 )
{
condition += " and ";
}
TExpression lc_expr = lcjrs.get( k ).expr;
lc_expr.remove( );
}
fc.condition = condition;
fromClauses.add( fc );
tableUsed[i] = true;
tableUsed[j] = true;
foundTableJoined = true;
}
}
}
}
if ( !foundTableJoined )
{
break;
}
}
// are all join conditions used?
for ( int i = 0; i < jrs.size( ); i++ )
{
JoinCondition jc = jrs.get( i );
if ( !jc.used )
{
for ( int j = fromClauses.size( ) - 1; j >= 0; j-- )
{
if ( isNameOrAliasOfTable( fromClauses.get( j ).joinTable,
jc.lefttable )
|| isNameOrAliasOfTable( fromClauses.get( j ).joinTable,
jc.righttable ) )
{
fromClauses.get( j ).condition += " and "
+ jc.expr.toString( );
jc.used = true;
jc.expr.remove( );
break;
}
}
}
}
for ( int i = 0; i < select.tables.size( ); i++ )
{
if ( !tableUsed[i] )
{
ErrorNo++;
ErrorMessage += String.format( "%sError %d, Message: %s",
System.getProperty( "line.separator" ),
ErrorNo,
"This table has no join condition: "
+ select.tables.getTable( i )
.getFullName( ) );
}
}
// link all join clause
for ( int i = 0; i < fromClauses.size( ); i++ )
{
FromClause fc = fromClauses.get( i );
// fromclause += System.getProperty("line.separator") +
// fc.joinClause
// +" "+fc.joinTable.getFullNameWithAliasString()+" on "+fc.condition;
fromclause += "\n"
+ fc.joinClause
+ " "
+ fc.joinTable.getFullNameWithAliasString( )
+ " on "
+ fc.condition;
}
for ( int k = select.joins.size( ) - 1; k > 0; k-- )
{
select.joins.removeJoin( k );
}
select.joins.getJoin( 0 ).setString( fromclause );
if ( ( select.getWhereClause( ).getCondition( ).getStartToken( ) == null )
|| ( select.getWhereClause( )
.getCondition( )
.toString( )
.trim( )
.length( ) == 0 ) )
{
// no where condition, remove WHERE keyword
select.getWhereClause( ).setString( " " );
}
}
}
else
{
analyzeSelect( select.getLeftStmt( ) );
analyzeSelect( select.getRightStmt( ) );
}
}
private String getExpressionTable( TExpression expr )
{
if ( expr.getObjectOperand( ) != null )
return expr.getObjectOperand( ).getObjectString( );
else if ( expr.getLeftOperand( ) != null
&& expr.getLeftOperand( ).getObjectOperand( ) != null )
return expr.getLeftOperand( ).getObjectOperand( ).getObjectString( );
else if ( expr.getRightOperand( ) != null
&& expr.getRightOperand( ).getObjectOperand( ) != null )
return expr.getRightOperand( )
.getObjectOperand( )
.getObjectString( );
else
return null;
}
public static void main( String args[] )
{
// String sqltext = "SELECT e.employee_id,\n" +
// " e.last_name,\n" +
// " <SUF>
// "FROM employees e,\n" +
// " departments d\n" ;
String sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id = d.department_id";
sqltext = "SELECT m.*, \n"
+ " altname.last_name last_name_student, \n"
+ " altname.first_name first_name_student, \n"
+ " ccu.date_joined, \n"
+ " ccu.last_login, \n"
+ " ccu.photo_id, \n"
+ " ccu.last_updated \n"
+ "FROM summit.mstr m, \n"
+ " summit.alt_name altname, \n"
+ " smmtccon.ccn_user ccu \n"
+ "WHERE m.id =?\n"
+ " AND m.id = altname.id(+) \n"
+ " AND m.id = ccu.id(+) \n"
+ " AND altname.grad_name_ind(+) = '*'";
// sqltext = "SELECT * \n" +
// "FROM summit.mstr m, \n" +
// " summit.alt_name altname, \n" +
// " smmtccon.ccn_user ccu \n" +
// //" uhelp.deg_coll deg \n" +
// "WHERE m.id = ? \n" +
// " AND m.id = altname.id(+) \n" +
// " AND m.id = ccu.id(+) \n" +
// " AND 'N' = ccu.admin(+) \n" +
// " AND altname.grad_name_ind(+) = '*'";
// sqltext = "SELECT ppp.project_name proj_name, \n" +
// " pr.role_title user_role \n" +
// "FROM jboss_admin.portal_application_location pal, \n" +
// " jboss_admin.portal_application pa, \n" +
// " jboss_admin.portal_user_app_location_role pualr, \n" +
// " jboss_admin.portal_location pl, \n" +
// " jboss_admin.portal_role pr, \n" +
// " jboss_admin.portal_pep_project ppp, \n" +
// " jboss_admin.portal_user pu \n" +
// "WHERE (pal.application_location_id = pualr.application_location_id \n"
// +
// " AND pu.jbp_uid = pualr.jbp_uid \n" +
// " AND pu.username = 'USERID') \n" +
// " AND pal.uidr_uid = pl.uidr_uid \n" +
// " AND pal.application_id = pa.application_id \n" +
// " AND pal.application_id = pr.application_id \n" +
// " AND pualr.role_id = pr.role_id \n" +
// " AND pualr.project_id = ppp.project_id \n" +
// " AND pa.application_id = 'APPID' ";
sqltext = "SELECT * \n"
+ "FROM smmtccon.ccn_menu menu, \n"
+ " smmtccon.ccn_page paget \n"
+ "WHERE ( menu.page_id = paget.page_id(+) ) \n"
+ " AND ( NOT enabled = 'N' ) \n"
+ " AND ( ( :parent_menu_id IS NULL \n"
+ " AND menu.parent_menu_id IS NULL ) \n"
+ " OR ( menu.parent_menu_id = :parent_menu_id ) ) \n"
+ "ORDER BY item_seq;";
sqltext = "select *\n"
+ "from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
+ " , ods_stg_pnb_stuf_pers_adr pas\n"
+ " , ods_stg_pnb_stuf_pers_nat nat\n"
+ " , ods_stg_pnb_stuf_adr adr\n"
+ " , ods_stg_pnb_stuf_np prs\n"
+ "where \n"
+ " pas.soort_adres = lst.soort_adres\n"
+ " and prs.id = nat.prs_id(+)\n"
+ " and adr.id = pas.adr_id\n"
+ " and prs.id = pas.prs_id\n"
+ " and lst.persoonssoort = 'PERSOON'\n"
+ " and pas.einddatumrelatie is null ";
sqltext = "select *\n"
+ " from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
+ " , ods_stg_pnb_stuf_np prs\n"
+ " , ods_stg_pnb_stuf_pers_adr pas\n"
+ " , ods_stg_pnb_stuf_pers_nat nat\n"
+ " , ods_stg_pnb_stuf_adr adr\n"
+ " where \n"
+ " pas.soort_adres = lst.soort_adres\n"
+ " and prs.id(+) = nat.prs_id\n"
+ " and adr.id = pas.adr_id\n"
+ " and prs.id = pas.prs_id\n"
+ " and lst.persoonssoort = 'PERSOON'\n"
+ " and pas.einddatumrelatie is null";
// sqltext = "SELECT ppp.project_name proj_name, \n"
// + " pr.role_title user_role \n"
// + "FROM jboss_admin.portal_application_location pal, \n"
// + " jboss_admin.portal_application pa, \n"
// + " jboss_admin.portal_user_app_location_role pualr, \n"
// + " jboss_admin.portal_location pl, \n"
// + " jboss_admin.portal_role pr, \n"
// + " jboss_admin.portal_pep_project ppp, \n"
// + " jboss_admin.portal_user pu \n"
// +
// "WHERE (pal.application_location_id = pualr.application_location_id \n"
// + " AND pu.jbp_uid = pualr.jbp_uid \n"
// + " AND pu.username = 'USERID') \n"
// + " AND pal.uidr_uid = pl.uidr_uid \n"
// + " AND pal.application_id = pa.application_id \n"
// + " AND pal.application_id = pr.application_id \n"
// + " AND pualr.role_id = pr.role_id \n"
// + " AND pualr.project_id = ppp.project_id \n"
// + " AND pa.application_id = 'APPID'";
//
// sqltext = "select *\n"
// + "from ods_trf_pnb_stuf_lijst_adrsrt2 lst\n"
// + " , ods_stg_pnb_stuf_np prs\n"
// + " , ods_stg_pnb_stuf_pers_adr pas\n"
// + " , ods_stg_pnb_stuf_pers_nat nat\n"
// + " , ods_stg_pnb_stuf_adr adr\n"
// + "where \n"
// + " pas.soort_adres = lst.soort_adres\n"
// + " and prs.id = nat.prs_id(+)\n"
// + " and adr.id = pas.adr_id\n"
// + " and prs.id = pas.prs_id\n"
// + " and lst.persoonssoort = 'PERSOON'\n"
// + " and pas.einddatumrelatie is null";
// sqltext = "select *\n"
// + "from ods_trf_pnb_stuf_lijst_adrsrt2 lst,\n"
// + " ods_stg_pnb_stuf_np prs,\n"
// + " ods_stg_pnb_stuf_pers_adr pas,\n"
// + " ods_stg_pnb_stuf_pers_nat nat,\n"
// + " ods_stg_pnb_stuf_adr adr\n"
// + "where pas.soort_adres = lst.soort_adres\n"
// + " and prs.id(+) = nat.prs_id\n"
// + " and adr.id = pas.adr_id\n"
// + " and prs.id = pas.prs_id\n"
// + " and lst.persoonssoort = 'PERSOON'\n"
// + " and pas.einddatumrelatie is null\n";
sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id = d.department_id(+)";
sqltext = "SELECT e.employee_id,\n"
+ " e.last_name,\n"
+ " e.department_id\n"
+ "FROM employees e,\n"
+ " departments d\n"
+ "WHERE e.department_id(+) = d.department_id";
System.out.println( "SQL with Oracle propriety joins" );
System.out.println( sqltext );
oracleJoinConverter converter = new oracleJoinConverter( sqltext );
if ( converter.convert( ) != 0 )
{
System.out.println( converter.getErrorMessage( ) );
}
else
{
System.out.println( "\nSQL in ANSI joins" );
System.out.println( converter.getQuery( ) );
}
}
} |
143245_32 | /*
* 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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.util.Locale;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.HttpParser;
import org.apache.tomcat.util.http.parser.MediaType;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten <[email protected]>
* @author Remy Maucherat
*/
public final class Response {
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
*/
protected MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
protected Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public OutputBuffer getOutputBuffer() {
return outputBuffer;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
if (v && !this.commited) {
this.commitTime = System.currentTimeMillis();
}
this.commited = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
// -------------------- Methods --------------------
public void reset()
throws IllegalStateException {
// Reset the headers only if this is the main request,
// not for included
contentType = null;
locale = DEFAULT_LOCALE;
contentLanguage = null;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
contentLength = -1;
charsetSet = false;
status = 200;
message = null;
headers.clear();
// Force the PrintWriter to flush its data to the output
// stream before resetting the output stream
//
// Reset the stream
if (commited) {
//String msg = sm.getString("servletOutputStreamImpl.reset.ise");
throw new IllegalStateException();
}
action(ActionCode.RESET, this);
}
public void finish() {
action(ActionCode.CLOSE, this);
}
public void acknowledge() {
action(ActionCode.ACK, this);
}
// -------------------- Headers --------------------
/**
* Warning: This method always returns <code>false<code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.addValue(name).setString( value );
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
if( name.equalsIgnoreCase( "Content-Language" ) ) {
// XXX XXX Need to construct Locale or something else
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the character encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = HttpParser.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
charsetSet = true;
this.characterEncoding = charsetValue;
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
contentWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
commitTime = -1;
errorException = null;
headers.clear();
// update counters
contentWritten=0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
}
| sustain/tomcat70 | java/org/apache/coyote/Response.java | 3,644 | // -------------------- Headers -------------------- | line_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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.util.Locale;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.HttpParser;
import org.apache.tomcat.util.http.parser.MediaType;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten <[email protected]>
* @author Remy Maucherat
*/
public final class Response {
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
*/
protected MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
protected Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public OutputBuffer getOutputBuffer() {
return outputBuffer;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
if (v && !this.commited) {
this.commitTime = System.currentTimeMillis();
}
this.commited = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
// -------------------- Methods --------------------
public void reset()
throws IllegalStateException {
// Reset the headers only if this is the main request,
// not for included
contentType = null;
locale = DEFAULT_LOCALE;
contentLanguage = null;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
contentLength = -1;
charsetSet = false;
status = 200;
message = null;
headers.clear();
// Force the PrintWriter to flush its data to the output
// stream before resetting the output stream
//
// Reset the stream
if (commited) {
//String msg = sm.getString("servletOutputStreamImpl.reset.ise");
throw new IllegalStateException();
}
action(ActionCode.RESET, this);
}
public void finish() {
action(ActionCode.CLOSE, this);
}
public void acknowledge() {
action(ActionCode.ACK, this);
}
// -------------------- Headers<SUF>
/**
* Warning: This method always returns <code>false<code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.addValue(name).setString( value );
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
if( name.equalsIgnoreCase( "Content-Language" ) ) {
// XXX XXX Need to construct Locale or something else
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the character encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = HttpParser.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
charsetSet = true;
this.characterEncoding = charsetValue;
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
contentWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
commitTime = -1;
errorException = null;
headers.clear();
// update counters
contentWritten=0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
}
|
7853_0 | package hu.indicium.speurtocht.domain;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@IdClass(ChallengeSubmissionId.class)
public class ChallengeSubmission {
@ManyToOne
@Id
private Team team;
@ManyToOne
@Id
private Challenge challenge;
private SubmissionState status;
private Instant submittedAt;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<FileSubmission> fileSubmission;
public ChallengeSubmission(Team team, Challenge challenge, MultipartFile[] files) throws IOException {
this.team = team;
this.challenge = challenge;
this.status = SubmissionState.PENDING;
this.submittedAt = Instant.now();
this.fileSubmission = Arrays.stream(files).map(file -> {
try {
return new FileSubmission(file);
} catch (IOException e) {
System.out.println(e);
throw new RuntimeException(e);
}
}).toList();
}
public void approve() {
this.status = SubmissionState.APPROVED;
}
// todo string met reden waarom
public void deny() {
this.status = SubmissionState.DENIED;
}
}
| svIndicium/intro-backend-en-admin-panel | src/main/java/hu/indicium/speurtocht/domain/ChallengeSubmission.java | 454 | // todo string met reden waarom | line_comment | nl | package hu.indicium.speurtocht.domain;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@IdClass(ChallengeSubmissionId.class)
public class ChallengeSubmission {
@ManyToOne
@Id
private Team team;
@ManyToOne
@Id
private Challenge challenge;
private SubmissionState status;
private Instant submittedAt;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<FileSubmission> fileSubmission;
public ChallengeSubmission(Team team, Challenge challenge, MultipartFile[] files) throws IOException {
this.team = team;
this.challenge = challenge;
this.status = SubmissionState.PENDING;
this.submittedAt = Instant.now();
this.fileSubmission = Arrays.stream(files).map(file -> {
try {
return new FileSubmission(file);
} catch (IOException e) {
System.out.println(e);
throw new RuntimeException(e);
}
}).toList();
}
public void approve() {
this.status = SubmissionState.APPROVED;
}
// todo string<SUF>
public void deny() {
this.status = SubmissionState.DENIED;
}
}
|
177505_9 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import bean.CartBean;
import dao.OrderDAO;
import dao.OrderProductDAO;
import model.hibernate.Order;
import model.hibernate.OrderProduct;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
/**
*
* @author Stefan
*/
public class CartController extends HttpServlet {
CartBean cartBean = new CartBean();
HttpSession session;
/* HTTP GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Stel de pagina in die bij deze controller hoort
String address = "cart.jsp";
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
/* HTTP POST request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set a variable for the address to the JSP file that'll be shown at runtime
String address;
// Create an instance of the order/orderProduct DAO & Model
OrderDAO orderDao = new OrderDAO();
OrderProductDAO orderProductDao = new OrderProductDAO();
Order order;
OrderProduct orderProduct;
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
/*
* Check if a customer is logged in prior to placing the order, and make
* sure products are present in the cart.
*/
if(
cartBean.getProduct().size() > 0 &&
cartBean.getCustomer() != null
) {
order = new Order();
order.setCustomer(cartBean.getCustomer());
order.setOrderDate(new Date());
orderDao.create(order);
List orderProductList = new LinkedList();
for(int i = 0; i < cartBean.getProduct().size(); i++) {
orderProduct = new OrderProduct();
orderProduct.setOrder(order);
orderProduct.setProduct(cartBean.getProduct().get(i).getProduct());
orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount());
orderProductDao.create(orderProduct);
orderProductList.add(orderProduct);
}
// Assign a new empty vector to the product vector
cartBean.setProduct(new Vector());
// Set the page that will be shown when the POST is made
address = "order_success.jsp";
} else {
// Set the page that will be shown when the POST is made
address = "order_failure.jsp";
}
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
} | svbeusekom/WEBShop | src/java/controller/CartController.java | 1,080 | // Doe een verzoek naar het adres | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import bean.CartBean;
import dao.OrderDAO;
import dao.OrderProductDAO;
import model.hibernate.Order;
import model.hibernate.OrderProduct;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
/**
*
* @author Stefan
*/
public class CartController extends HttpServlet {
CartBean cartBean = new CartBean();
HttpSession session;
/* HTTP GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Stel de pagina in die bij deze controller hoort
String address = "cart.jsp";
// Doe een<SUF>
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
/* HTTP POST request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set a variable for the address to the JSP file that'll be shown at runtime
String address;
// Create an instance of the order/orderProduct DAO & Model
OrderDAO orderDao = new OrderDAO();
OrderProductDAO orderProductDao = new OrderProductDAO();
Order order;
OrderProduct orderProduct;
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
/*
* Check if a customer is logged in prior to placing the order, and make
* sure products are present in the cart.
*/
if(
cartBean.getProduct().size() > 0 &&
cartBean.getCustomer() != null
) {
order = new Order();
order.setCustomer(cartBean.getCustomer());
order.setOrderDate(new Date());
orderDao.create(order);
List orderProductList = new LinkedList();
for(int i = 0; i < cartBean.getProduct().size(); i++) {
orderProduct = new OrderProduct();
orderProduct.setOrder(order);
orderProduct.setProduct(cartBean.getProduct().get(i).getProduct());
orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount());
orderProductDao.create(orderProduct);
orderProductList.add(orderProduct);
}
// Assign a new empty vector to the product vector
cartBean.setProduct(new Vector());
// Set the page that will be shown when the POST is made
address = "order_success.jsp";
} else {
// Set the page that will be shown when the POST is made
address = "order_failure.jsp";
}
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
} |
78750_24 | package be.fomp.carcassonne.utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import be.fomp.carcassonne.game.objects.AreaType;
import be.fomp.carcassonne.model.Area;
import be.fomp.carcassonne.model.Follower;
import be.fomp.carcassonne.model.Player;
import be.fomp.carcassonne.model.Tile;
import be.fomp.carcassonne.model.Zone;
/**
* Performs scoring calculations by recursively going over the whole map
* @author sven
*
*/
public final class ScoreCalculator {
/**
* - Calculates the score between game rounds
* - Assigns that score to the players
* - Restores the players followers
*
* //TODO another way of calculating scores would be to keep
* track of all followers and iterate over them.
*
* @param rootTile can be any connected tile
*/
public static final void calculateScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateCloisterScore(az); break;
case CITY:
case CITY2: calculateCityScore(az); break;
case ROAD: calculateRoadScore(az); break;
default:break;
}
}
}
// (First Edition, included in the English version) Farm Scoring Rules:
//
// 1. Identify each completed city.
//
// 2. Count the total number of farmers adjacent to the city in all
// adjacent fields. These farmers are said to supply the city.
//
// 3. The player with the most farmers supplying the city earns the 4 points
// (5 if that player also has a pig in an adjacent field).
// If the completed city is besieged, earns 8 points (10 if that player
// also has a pig on that field) instead.
//
// 4. Consider placing a token or a marker of some sort in each scored city;
// this may make it easier to accurately tally the points by identifying the
// cities that have already been scored.
/**
* Calculates the scores at the end of the game
* Assigns it to the players
* Restores the followers
**/
public static final void calculateEndScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
Set<Zone> completedCities = new HashSet<Zone>();
Set<Zone> fields = new HashSet<Zone>();
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(az.getAreaType() == AreaType.CITY || az.getAreaType() == AreaType.CITY2)
if(isComplete(z)) completedCities.add(z);
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateEndCloisterScore(az); break;
case CITY:
case CITY2: calculateEndCityScore(az);
break;
case ROAD: calculateEndRoadScore(az); break;
case FIELD: fields.add(z);
default:break;
}
}
calculateEndFieldScore(fields, completedCities);
}
/**
* A follower was scored so it can be returned to the player
* @param f the follower that was scored
*/
private static void restoreFollower(Follower f){
Player p = f.getOwner();
p.setFollowers(p.getFollowers() + 1);
//Clean up follower from the area
f.setOwner(null);
f.getLocation().removeFollower();
f.setLocation(null);
}
private static final void calculateCloisterScore(Area cloister){
Tile t = cloister.getLocation();
if(!TileUtils.isCompletelySurrounded(t)) return;
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getCloisterScore());
restoreFollower(f);
}
private static final void calculateEndCloisterScore(Area cloister){
Tile t = cloister.getLocation();
int surroundingTiles = TileUtils.countSurroundingTiles(t);
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getEndCloisterScore(surroundingTiles));
restoreFollower(f);
}
/**
* From analysis:
* Stad: Een stad is compleet als hij volledig door muren omringd is.
* De speler met een ridder in de stad scoort 2 punten voor elke tegel
* waarop de stad ligt plus 2 punten voor elk schildje dat in de stad ligt.
*
* Uitzondering: Als de speler een stad vervolledigt dat uit 2 tegels bestaat
* krijgt hij maar 1 punt per tegel plus 1 per schild.
*
* De spelers met de meeste volgers krijgen elk de totale score
* @param city
*/
private static final void calculateCityScore(Area city){
Zone zone = city.getZone();
if(!isComplete(zone)) return; //If the area is not complete, return
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers = 0;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f);
}
private static final void calculateEndCityScore(Area city){
Zone zone = city.getZone();
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getEndCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateRoadScore(Area road) {
Zone zone = road.getZone();
if(!isComplete(zone)) return;
int tileCount = zone.getTiles().size();
int score = Ruleset.getRoadScore(tileCount);
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndRoadScore(Area road) {
Zone zone = road.getZone();
int tileCount = zone.getTiles().size();
int score = Ruleset.getEndRoadScore(tileCount);
int mostFollowers = 1;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndFieldScore(Set<Zone> fields, Set<Zone> cities) {
Set<Follower> checkedFollowers = new HashSet<Follower>();
for(Zone city: cities)
for(Zone field : city.getNeigboringZones())
if(fields.contains(field) && field.hasFollowers()) {
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = field.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + Ruleset.getEndFarmerScore(mostFollowers));
}
checkedFollowers.addAll(followers); //Tag followers for removal
}
for(Follower f : checkedFollowers) restoreFollower(f); //Clean up followers
}
private static final boolean isComplete(Zone z) {
for(Area a : z.getAreas())
{
Area[] border = a.getLocation().getBorder();
Area[] borderConnections = a.getLocation().getBorderConnections();
for(int i=0; i< borderConnections.length; i++)
if(z == border[i].getZone() && borderConnections[i] == null)
return false;
}
return true;
}
private static Map<Player, Integer> countPlayerFollowers(Set<Follower> followers) {
Map<Player, Integer> returnValue = new HashMap<Player, Integer>();
int followerCounter = 1;
for(Follower f: followers) {
Player p = f.getOwner();
if(returnValue.containsKey(p)){
int newCount = returnValue.get(p) + 1;
returnValue.put(p, newCount);
if(followerCounter < newCount) followerCounter = newCount;
}
else
returnValue.put(p, 1);
}
return returnValue;
}
}
| svenmeys/Carcassonne | src/be/fomp/carcassonne/utils/ScoreCalculator.java | 3,416 | /**
* From analysis:
* Stad: Een stad is compleet als hij volledig door muren omringd is.
* De speler met een ridder in de stad scoort 2 punten voor elke tegel
* waarop de stad ligt plus 2 punten voor elk schildje dat in de stad ligt.
*
* Uitzondering: Als de speler een stad vervolledigt dat uit 2 tegels bestaat
* krijgt hij maar 1 punt per tegel plus 1 per schild.
*
* De spelers met de meeste volgers krijgen elk de totale score
* @param city
*/ | block_comment | nl | package be.fomp.carcassonne.utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import be.fomp.carcassonne.game.objects.AreaType;
import be.fomp.carcassonne.model.Area;
import be.fomp.carcassonne.model.Follower;
import be.fomp.carcassonne.model.Player;
import be.fomp.carcassonne.model.Tile;
import be.fomp.carcassonne.model.Zone;
/**
* Performs scoring calculations by recursively going over the whole map
* @author sven
*
*/
public final class ScoreCalculator {
/**
* - Calculates the score between game rounds
* - Assigns that score to the players
* - Restores the players followers
*
* //TODO another way of calculating scores would be to keep
* track of all followers and iterate over them.
*
* @param rootTile can be any connected tile
*/
public static final void calculateScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateCloisterScore(az); break;
case CITY:
case CITY2: calculateCityScore(az); break;
case ROAD: calculateRoadScore(az); break;
default:break;
}
}
}
// (First Edition, included in the English version) Farm Scoring Rules:
//
// 1. Identify each completed city.
//
// 2. Count the total number of farmers adjacent to the city in all
// adjacent fields. These farmers are said to supply the city.
//
// 3. The player with the most farmers supplying the city earns the 4 points
// (5 if that player also has a pig in an adjacent field).
// If the completed city is besieged, earns 8 points (10 if that player
// also has a pig on that field) instead.
//
// 4. Consider placing a token or a marker of some sort in each scored city;
// this may make it easier to accurately tally the points by identifying the
// cities that have already been scored.
/**
* Calculates the scores at the end of the game
* Assigns it to the players
* Restores the followers
**/
public static final void calculateEndScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
Set<Zone> completedCities = new HashSet<Zone>();
Set<Zone> fields = new HashSet<Zone>();
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(az.getAreaType() == AreaType.CITY || az.getAreaType() == AreaType.CITY2)
if(isComplete(z)) completedCities.add(z);
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateEndCloisterScore(az); break;
case CITY:
case CITY2: calculateEndCityScore(az);
break;
case ROAD: calculateEndRoadScore(az); break;
case FIELD: fields.add(z);
default:break;
}
}
calculateEndFieldScore(fields, completedCities);
}
/**
* A follower was scored so it can be returned to the player
* @param f the follower that was scored
*/
private static void restoreFollower(Follower f){
Player p = f.getOwner();
p.setFollowers(p.getFollowers() + 1);
//Clean up follower from the area
f.setOwner(null);
f.getLocation().removeFollower();
f.setLocation(null);
}
private static final void calculateCloisterScore(Area cloister){
Tile t = cloister.getLocation();
if(!TileUtils.isCompletelySurrounded(t)) return;
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getCloisterScore());
restoreFollower(f);
}
private static final void calculateEndCloisterScore(Area cloister){
Tile t = cloister.getLocation();
int surroundingTiles = TileUtils.countSurroundingTiles(t);
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getEndCloisterScore(surroundingTiles));
restoreFollower(f);
}
/**
* From analysis:
<SUF>*/
private static final void calculateCityScore(Area city){
Zone zone = city.getZone();
if(!isComplete(zone)) return; //If the area is not complete, return
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers = 0;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f);
}
private static final void calculateEndCityScore(Area city){
Zone zone = city.getZone();
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getEndCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateRoadScore(Area road) {
Zone zone = road.getZone();
if(!isComplete(zone)) return;
int tileCount = zone.getTiles().size();
int score = Ruleset.getRoadScore(tileCount);
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndRoadScore(Area road) {
Zone zone = road.getZone();
int tileCount = zone.getTiles().size();
int score = Ruleset.getEndRoadScore(tileCount);
int mostFollowers = 1;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndFieldScore(Set<Zone> fields, Set<Zone> cities) {
Set<Follower> checkedFollowers = new HashSet<Follower>();
for(Zone city: cities)
for(Zone field : city.getNeigboringZones())
if(fields.contains(field) && field.hasFollowers()) {
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = field.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + Ruleset.getEndFarmerScore(mostFollowers));
}
checkedFollowers.addAll(followers); //Tag followers for removal
}
for(Follower f : checkedFollowers) restoreFollower(f); //Clean up followers
}
private static final boolean isComplete(Zone z) {
for(Area a : z.getAreas())
{
Area[] border = a.getLocation().getBorder();
Area[] borderConnections = a.getLocation().getBorderConnections();
for(int i=0; i< borderConnections.length; i++)
if(z == border[i].getZone() && borderConnections[i] == null)
return false;
}
return true;
}
private static Map<Player, Integer> countPlayerFollowers(Set<Follower> followers) {
Map<Player, Integer> returnValue = new HashMap<Player, Integer>();
int followerCounter = 1;
for(Follower f: followers) {
Player p = f.getOwner();
if(returnValue.containsKey(p)){
int newCount = returnValue.get(p) + 1;
returnValue.put(p, newCount);
if(followerCounter < newCount) followerCounter = newCount;
}
else
returnValue.put(p, 1);
}
return returnValue;
}
}
|
109086_30 | // Package
package com.application.media.controller;
// Imports
import com.application.media.exceptions.BadRequestException;
import com.application.media.model.User;
import com.application.media.repository.UserRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@CrossOrigin(origins = "${ALLOWED_ORIGINS}")
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* @param user - Create new user
* @return - Returns the new user
*/
@PostMapping("/create")
public User createUser(@RequestBody User user) {
System.out.println(user.getId());
System.out.println(user.getName());
System.out.println(user.getLocation());
return userRepository.save(user);
}
/**
* @return - Returns all users in the database
*/
@GetMapping("/getAll")
public List<User> getAllUsers() {
return userRepository.findAll();
}
/**
* @param userId - ID of the user
* @return - Returns the user find by an ID
*/
@GetMapping("/{userId}")
public Optional<User> getUserById(@PathVariable Long userId) {
return userRepository.findById(userId);
}
/**
* @param userId - ID of the user
* @param updatedUser - RequestBody
* @return - Returns the updated user
*/
@PutMapping("/update/{userId}")
public User updateUser(@PathVariable Long userId, @RequestBody User updatedUser) {
// First find the user by ID
Optional<User> existingUser = userRepository.findById(userId);
// Check if the user is present
if (existingUser.isPresent()) {
// Get the correct user
User user = existingUser.get();
// Change the facts of the user when needed
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
user.setLocation(updatedUser.getLocation());
// Return the updated user
return userRepository.save(user);
} else {
// No user founded, return nothing
return null;
}
}
/**
* @param userId - ID of the user
* @param updateUserPassword - RequestBody
* @return - Returns the updated password of the user
*/
@PutMapping("/updatePassword/{userId}")
public User updateUserPassword(@PathVariable Long userId, @RequestBody User updateUserPassword) {
// First find the user by ID
Optional<User> existingUserPassword = userRepository.findById(userId);
// Check if the user is present
if (existingUserPassword.isPresent()) {
// get the correct user
User user = existingUserPassword.get();
// Change the password of the user when needed
user.setPassword(updateUserPassword.getPassword());
// Return the updated user
return userRepository.save(user);
} else {
// No user founded, return nothing
return null;
}
}
/**
* @param userId - ID of the user
* @return - Returns the user that is deleted
*/
@DeleteMapping("/delete/{userId}")
public User deleteUser(@PathVariable Long userId) {
// Find the user by ID
Optional<User> optionalUser = this.userRepository.findById(userId);
// Check if the user is present
if (optionalUser.isEmpty()) {
throw new BadRequestException("Cannot delete account with id=" + userId);
}
// Get the correct user
User user = optionalUser.get();
// Delete the user
this.userRepository.deleteById(userId);
// Return the user that is deleted
return user;
}
/**
* @param loginUser - RequestBody
* @return - Returns of the user is logged in
*/
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody User loginUser) {
// Find the user by ID
Optional<User> existingUser = userRepository.findById(loginUser.getId());
// Check if the user is present and if the user get the correct password
if (existingUser.isPresent() && existingUser.get().getPassword().equals(loginUser.getPassword())) {
// Generate a new token
String token = generateToken(existingUser.get().getId(), existingUser.get().getEmail());
// Returns the new generated token
return ResponseEntity.ok(token);
} else {
// Invalid login details
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Ongeldige inloggegevens");
}
}
/**
* @param userId - ID of the user
* @param userEmail - Email of the user
* @return - Returns a new generated token
*/
private String generateToken(Long userId, String userEmail) {
long expirationTime = 864_000_000; // 10 dagen in milliseconden
String secret = "jouw_geheime_sleutel"; // Vervang dit door een complexe geheime sleutel
return Jwts.builder().setSubject(userId.toString()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + expirationTime)).claim("email", userEmail).signWith(SignatureAlgorithm.HS512, secret).compact();
}
} | svenmouwen/Enterprise-Web-Application-College-Project- | back-end/media/src/main/java/com/application/media/controller/UserController.java | 1,467 | // 10 dagen in milliseconden | line_comment | nl | // Package
package com.application.media.controller;
// Imports
import com.application.media.exceptions.BadRequestException;
import com.application.media.model.User;
import com.application.media.repository.UserRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@CrossOrigin(origins = "${ALLOWED_ORIGINS}")
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* @param user - Create new user
* @return - Returns the new user
*/
@PostMapping("/create")
public User createUser(@RequestBody User user) {
System.out.println(user.getId());
System.out.println(user.getName());
System.out.println(user.getLocation());
return userRepository.save(user);
}
/**
* @return - Returns all users in the database
*/
@GetMapping("/getAll")
public List<User> getAllUsers() {
return userRepository.findAll();
}
/**
* @param userId - ID of the user
* @return - Returns the user find by an ID
*/
@GetMapping("/{userId}")
public Optional<User> getUserById(@PathVariable Long userId) {
return userRepository.findById(userId);
}
/**
* @param userId - ID of the user
* @param updatedUser - RequestBody
* @return - Returns the updated user
*/
@PutMapping("/update/{userId}")
public User updateUser(@PathVariable Long userId, @RequestBody User updatedUser) {
// First find the user by ID
Optional<User> existingUser = userRepository.findById(userId);
// Check if the user is present
if (existingUser.isPresent()) {
// Get the correct user
User user = existingUser.get();
// Change the facts of the user when needed
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
user.setLocation(updatedUser.getLocation());
// Return the updated user
return userRepository.save(user);
} else {
// No user founded, return nothing
return null;
}
}
/**
* @param userId - ID of the user
* @param updateUserPassword - RequestBody
* @return - Returns the updated password of the user
*/
@PutMapping("/updatePassword/{userId}")
public User updateUserPassword(@PathVariable Long userId, @RequestBody User updateUserPassword) {
// First find the user by ID
Optional<User> existingUserPassword = userRepository.findById(userId);
// Check if the user is present
if (existingUserPassword.isPresent()) {
// get the correct user
User user = existingUserPassword.get();
// Change the password of the user when needed
user.setPassword(updateUserPassword.getPassword());
// Return the updated user
return userRepository.save(user);
} else {
// No user founded, return nothing
return null;
}
}
/**
* @param userId - ID of the user
* @return - Returns the user that is deleted
*/
@DeleteMapping("/delete/{userId}")
public User deleteUser(@PathVariable Long userId) {
// Find the user by ID
Optional<User> optionalUser = this.userRepository.findById(userId);
// Check if the user is present
if (optionalUser.isEmpty()) {
throw new BadRequestException("Cannot delete account with id=" + userId);
}
// Get the correct user
User user = optionalUser.get();
// Delete the user
this.userRepository.deleteById(userId);
// Return the user that is deleted
return user;
}
/**
* @param loginUser - RequestBody
* @return - Returns of the user is logged in
*/
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody User loginUser) {
// Find the user by ID
Optional<User> existingUser = userRepository.findById(loginUser.getId());
// Check if the user is present and if the user get the correct password
if (existingUser.isPresent() && existingUser.get().getPassword().equals(loginUser.getPassword())) {
// Generate a new token
String token = generateToken(existingUser.get().getId(), existingUser.get().getEmail());
// Returns the new generated token
return ResponseEntity.ok(token);
} else {
// Invalid login details
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Ongeldige inloggegevens");
}
}
/**
* @param userId - ID of the user
* @param userEmail - Email of the user
* @return - Returns a new generated token
*/
private String generateToken(Long userId, String userEmail) {
long expirationTime = 864_000_000; // 10 dagen<SUF>
String secret = "jouw_geheime_sleutel"; // Vervang dit door een complexe geheime sleutel
return Jwts.builder().setSubject(userId.toString()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + expirationTime)).claim("email", userEmail).signWith(SignatureAlgorithm.HS512, secret).compact();
}
} |
38448_2 | package gui;
import assets.Artist;
import assets.Festival;
import assets.Performance;
import assets.Stage;
import gui.AgendaForm;
import javax.swing.*;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* Created by Stijn on 6-2-2017.
*/
public class Main {
public static AgendaForm mp;
public static Festival festival;
public static LocalDateTime currentTime = LocalDateTime.MIN;
public static void main(String[] args) throws IOException {
createTestFest();
//try {
mp = new AgendaForm();
// }catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Velden niet juist ingevoerd");
// }
}
public JFrame getMainPanel(){
return mp;
}
public static void createTestFest(){
festival = new Festival(10000, 10, LocalDate.parse("2017-05-23", DateTimeFormatter.ISO_DATE), LocalTime.parse("06:00"), LocalTime.parse("23:00"), "testfest");
festival.addStage(new Stage("Stage1", "", festival.getStages().size()));
festival.addStage(new Stage("Stage2", "", festival.getStages().size()));
festival.addStage(new Stage("Stage3", "", festival.getStages().size()));
// festival.addPerformance(new Performance(new Artist("example1", "gen1", 2), festival.getStage(0), LocalTime.parse("05:31"), LocalTime.parse("07:15")));
// festival.addPerformance(new Performance(new Artist("example2", "gen1", 4), festival.getStage(1 ), LocalTime.parse("09:17"), LocalTime.parse("12:47")));
// festival.addPerformance(new Performance(new Artist("example3", "gen2", 10000), festival.getStage(2), LocalTime.parse("22:15"), LocalTime.parse("23:55")));
// festival.addPerformance(new Performance(new Artist("example4", "gen3", 1000), festival.getStage(0), LocalTime.parse("00:11"), LocalTime.parse("02:34")));
// festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("03:23"), LocalTime.parse("05:16")));
// festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("13:06"), LocalTime.parse("15:00")));
// festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("17:12"), LocalTime.parse("21:27")));
festival.addPerformance(new Performance(new Artist("example1", "gen1", 2), festival.getStage(0), LocalTime.parse("05:31"), LocalTime.parse("08:15")));
festival.addPerformance(new Performance(new Artist("example2", "gen1", 4), festival.getStage(1 ), LocalTime.parse("07:40"), LocalTime.parse("11:47")));
festival.addPerformance(new Performance(new Artist("example3", "gen2", 10000), festival.getStage(2), LocalTime.parse("18:02"), LocalTime.parse("23:00")));
festival.addPerformance(new Performance(new Artist("example4", "gen3", 1000), festival.getStage(0), LocalTime.parse("00:01"), LocalTime.parse("03:34")));
festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("04:50"), LocalTime.parse("06:16")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("13:06"), LocalTime.parse("15:00")));
festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("14:45"), LocalTime.parse("18:27")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("01:06"), LocalTime.parse("05:10")));
festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("10:23"), LocalTime.parse("13:16")));
festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("22:00"), LocalTime.parse("23:59")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("22:30"), LocalTime.parse("23:59")));
}
}
| svgils/TIB1-FestivalPlanner | src/gui/Main.java | 1,388 | // JOptionPane.showMessageDialog(null, "Velden niet juist ingevoerd"); | line_comment | nl | package gui;
import assets.Artist;
import assets.Festival;
import assets.Performance;
import assets.Stage;
import gui.AgendaForm;
import javax.swing.*;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* Created by Stijn on 6-2-2017.
*/
public class Main {
public static AgendaForm mp;
public static Festival festival;
public static LocalDateTime currentTime = LocalDateTime.MIN;
public static void main(String[] args) throws IOException {
createTestFest();
//try {
mp = new AgendaForm();
// }catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Velden<SUF>
// }
}
public JFrame getMainPanel(){
return mp;
}
public static void createTestFest(){
festival = new Festival(10000, 10, LocalDate.parse("2017-05-23", DateTimeFormatter.ISO_DATE), LocalTime.parse("06:00"), LocalTime.parse("23:00"), "testfest");
festival.addStage(new Stage("Stage1", "", festival.getStages().size()));
festival.addStage(new Stage("Stage2", "", festival.getStages().size()));
festival.addStage(new Stage("Stage3", "", festival.getStages().size()));
// festival.addPerformance(new Performance(new Artist("example1", "gen1", 2), festival.getStage(0), LocalTime.parse("05:31"), LocalTime.parse("07:15")));
// festival.addPerformance(new Performance(new Artist("example2", "gen1", 4), festival.getStage(1 ), LocalTime.parse("09:17"), LocalTime.parse("12:47")));
// festival.addPerformance(new Performance(new Artist("example3", "gen2", 10000), festival.getStage(2), LocalTime.parse("22:15"), LocalTime.parse("23:55")));
// festival.addPerformance(new Performance(new Artist("example4", "gen3", 1000), festival.getStage(0), LocalTime.parse("00:11"), LocalTime.parse("02:34")));
// festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("03:23"), LocalTime.parse("05:16")));
// festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("13:06"), LocalTime.parse("15:00")));
// festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("17:12"), LocalTime.parse("21:27")));
festival.addPerformance(new Performance(new Artist("example1", "gen1", 2), festival.getStage(0), LocalTime.parse("05:31"), LocalTime.parse("08:15")));
festival.addPerformance(new Performance(new Artist("example2", "gen1", 4), festival.getStage(1 ), LocalTime.parse("07:40"), LocalTime.parse("11:47")));
festival.addPerformance(new Performance(new Artist("example3", "gen2", 10000), festival.getStage(2), LocalTime.parse("18:02"), LocalTime.parse("23:00")));
festival.addPerformance(new Performance(new Artist("example4", "gen3", 1000), festival.getStage(0), LocalTime.parse("00:01"), LocalTime.parse("03:34")));
festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("04:50"), LocalTime.parse("06:16")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("13:06"), LocalTime.parse("15:00")));
festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("14:45"), LocalTime.parse("18:27")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("01:06"), LocalTime.parse("05:10")));
festival.addPerformance(new Performance(new Artist("example5", "gen3", 1000), festival.getStage(2), LocalTime.parse("10:23"), LocalTime.parse("13:16")));
festival.addPerformance(new Performance(new Artist("example7", "gen3", 1000), festival.getStage(0), LocalTime.parse("22:00"), LocalTime.parse("23:59")));
festival.addPerformance(new Performance(new Artist("example6", "gen3", 1000), festival.getStage(1), LocalTime.parse("22:30"), LocalTime.parse("23:59")));
}
}
|
3004_12 | //jDownloader - Downloadmanager
//Copyright (C) 2012 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, 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 warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "mijnbestand.nl" }, urls = { "http://(www\\.)?mijnbestand\\.nl/(B|b)estand\\-[A-Z0-9]+" }, flags = { 0 })
public class MijnBestandNl extends PluginForHost {
public MijnBestandNl(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://www.mijnbestand.nl/AV";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(link.getDownloadURL());
if (br.getURL().equals("http://www.mijnbestand.nl/")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filename = br.getRegex("<title>([^<>\"]*?) downloaden</title>").getMatch(0);
if (filename == null) filename = br.getRegex("class=\"share_title\">([^<>\"]*?) delen via E\\-mail</div>").getMatch(0);
if (filename == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
link.setName(Encoding.htmlDecode(filename.trim()));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
br.postPage(br.getURL(), "download=start");
String dllink = br.getRegex("\"((B|b)estand\\-[A-Z0-9]+\\&download=[^<>\"/]*?)\"").getMatch(0);
if (dllink == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dllink = "http://www.mijnbestand.nl/" + dllink;
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | svn2github/jdownloader | src/jd/plugins/hoster/MijnBestandNl.java | 1,036 | //(www\\.)?mijnbestand\\.nl/(B|b)estand\\-[A-Z0-9]+" }, flags = { 0 })
| line_comment | nl | //jDownloader - Downloadmanager
//Copyright (C) 2012 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, 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 warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "mijnbestand.nl" }, urls = { "http://(www\\.)?mijnbestand\\.nl/(B|b)estand\\-[A-Z0-9]+" },<SUF>
public class MijnBestandNl extends PluginForHost {
public MijnBestandNl(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://www.mijnbestand.nl/AV";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(link.getDownloadURL());
if (br.getURL().equals("http://www.mijnbestand.nl/")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filename = br.getRegex("<title>([^<>\"]*?) downloaden</title>").getMatch(0);
if (filename == null) filename = br.getRegex("class=\"share_title\">([^<>\"]*?) delen via E\\-mail</div>").getMatch(0);
if (filename == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
link.setName(Encoding.htmlDecode(filename.trim()));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
br.postPage(br.getURL(), "download=start");
String dllink = br.getRegex("\"((B|b)estand\\-[A-Z0-9]+\\&download=[^<>\"/]*?)\"").getMatch(0);
if (dllink == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dllink = "http://www.mijnbestand.nl/" + dllink;
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
204182_1 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* MinMaxExtension.java
* Copyright (C) 2004 Stijn Lievens
*
*/
package weka.classifiers.monotone;
import weka.classifiers.Classifier;
import weka.classifiers.monotone.util.InstancesUtil;
import weka.core.Capabilities;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import java.util.Enumeration;
import java.util.Vector;
/**
<!-- globalinfo-start -->
* This class is an implementation of the minimal and maximal extension.<br/>
* All attributes and the class are assumed to be ordinal. The order of the ordinal attributes is determined by the internal codes used by WEKA.<br/>
* <br/>
* Further information regarding these algorithms can be found in:<br/>
* <br/>
* S. Lievens, B. De Baets, K. Cao-Van (2006). A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting. Annals of Operations Research..<br/>
* <br/>
* Kim Cao-Van (2003). Supervised ranking: from semantics to algorithms.<br/>
* <br/>
* Stijn Lievens (2004). Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken.<br/>
* <br/>
* For more information about supervised ranking, see<br/>
* <br/>
* http://users.ugent.be/~slievens/supervised_ranking.php
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{Lievens2006,
* author = {S. Lievens and B. De Baets and K. Cao-Van},
* journal = {Annals of Operations Research},
* title = {A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting},
* year = {2006}
* }
*
* @phdthesis{Cao-Van2003,
* author = {Kim Cao-Van},
* school = {Ghent University},
* title = {Supervised ranking: from semantics to algorithms},
* year = {2003}
* }
*
* @mastersthesis{Lievens2004,
* author = {Stijn Lievens},
* school = {Ghent University},
* title = {Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken},
* year = {2004}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -M
* Use maximal extension (default: minimal extension)</pre>
*
<!-- options-end -->
*
* @author Stijn Lievens ([email protected])
* @version $Revision: 1.1 $
*/
public class MinMaxExtension
extends Classifier
implements TechnicalInformationHandler {
/** for serialization */
private static final long serialVersionUID = 8505830465540027104L;
/**
* The training instances.
*/
private Instances m_data;
/**
* parameter for choice between min extension and max extension
*/
private boolean m_min = true;
/**
* Returns a string describing the classifier.
* @return a description suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"This class is an implementation of the "
+ "minimal and maximal extension.\n"
+ "All attributes and the class are assumed to be ordinal. The order of "
+ "the ordinal attributes is determined by the internal codes used by "
+ "WEKA.\n\n"
+ "Further information regarding these algorithms can be found in:\n\n"
+ getTechnicalInformation().toString() + "\n\n"
+ "For more information about supervised ranking, see\n\n"
+ "http://users.ugent.be/~slievens/supervised_ranking.php";
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
TechnicalInformation additional;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "S. Lievens and B. De Baets and K. Cao-Van");
result.setValue(Field.YEAR, "2006");
result.setValue(Field.TITLE, "A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting");
result.setValue(Field.JOURNAL, "Annals of Operations Research");
additional = result.add(Type.PHDTHESIS);
additional.setValue(Field.AUTHOR, "Kim Cao-Van");
additional.setValue(Field.YEAR, "2003");
additional.setValue(Field.TITLE, "Supervised ranking: from semantics to algorithms");
additional.setValue(Field.SCHOOL, "Ghent University");
additional = result.add(Type.MASTERSTHESIS);
additional.setValue(Field.AUTHOR, "Stijn Lievens");
additional.setValue(Field.YEAR, "2004");
additional.setValue(Field.TITLE, "Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken");
additional.setValue(Field.SCHOOL, "Ghent University");
return result;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Builds the classifier. This is in fact nothing else than copying
* the given instances.
*
* @param instances the training examples
* @throws Exception if the classifier is not able to handle the
* <code> instances </code>.
*/
public void buildClassifier(Instances instances) throws Exception {
getCapabilities().testWithFail(instances);
// copy the dataset
m_data = new Instances(instances);
// new dataset in which examples with missing class value are removed
m_data.deleteWithMissingClass();
}
/**
* Classifies the given instance.
*
* @param instance the instance to be classified
* @return a double representing the internal value
* of the label that is assigned to the given instance
*/
public double classifyInstance(Instance instance) {
double value;
if (m_min == true) {
value = 0;
for (int i = 0; i < m_data.numInstances(); i++) {
Instance i2 = m_data.instance(i);
if (InstancesUtil.smallerOrEqual(i2, instance) == true) {
value = Math.max(value, i2.classValue());
}
}
}
else {
value = m_data.classAttribute().numValues() - 1;
for (int i = 0; i < m_data.numInstances(); i++) {
Instance i2 = m_data.instance(i);
if (InstancesUtil.smallerOrEqual(instance, i2) == true) {
value = Math.min(value, i2.classValue());
}
}
}
return value;
}
/**
* After calling this method, the next classification will use the minimal
* extension.
*/
public void setMinExtension() {
m_min = true;
}
/**
* After calling this method, the next classification will use the maximal
* extension.
*/
public void setMaxExtension() {
m_min = false;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String minMaxExtensionTipText() {
return "If true, the minimal extension of the algorithm is chosen, "
+ "otherwise, it is the maximal extension";
}
/**
* Return if the minimal extension is in effect.
*
* @return <code> true </code> if the minimal is in effect,
* <code> false </code> otherwise
*/
public boolean getMinMaxExtension() {
return m_min;
}
/**
* Chooses between the minimal and maximal extension of the algorithm.
* If <code> min </code> is <code> true </code> then the minimal extension
* wil be in effect, otherwise it will the maximal extension.
*
* @param min do we choose the minimal extension
*/
public void setMinMaxExtension(boolean min) {
m_min = min;
}
/**
* Parses the options for this object. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -M
* Use maximal extension (default: minimal extension)</pre>
*
<!-- options-end -->
*
* @param options an array of strings containing the options for the classifier
* @throws Exception if
*/
public void setOptions(String[] options) throws Exception {
m_min = !Utils.getFlag('M',options); // check if -M option is present
super.setOptions(options);
}
/**
* Gets the current settings of this classifier.
*
* @return an array of strings suitable for passing to
* <code> setOptions </code>
*/
public String[] getOptions() {
int i;
Vector result;
String[] options;
result = new Vector();
options = super.getOptions();
for (i = 0; i < options.length; i++)
result.add(options[i]);
if (!m_min)
result.add("-M");
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Produces an enumeration describing the available options for
* this classifier.
*
* @return an enumeration with the available options.
*/
public Enumeration listOptions() {
Vector options = new Vector();
Enumeration enm = super.listOptions();
while (enm.hasMoreElements())
options.addElement(enm.nextElement());
String s = "\tUse maximal extension (default: minimal extension)";
options.add(new Option(s, "M", 0, "-M"));
return options.elements();
}
/**
* returns a string representation of this classifier
*
* @return the classname
*/
public String toString() {
return this.getClass().getName();
}
/**
* Main method for testing this class and for using it from the
* command line.
*
* @param args array of options for both the classifier <code>
* MinMaxExtension </code> and for <code> evaluateModel </code>
*/
public static void main(String[] args) {
runClassifier(new MinMaxExtension(), args);
}
}
| svn2github/weka | tags/before_fixes_for_FilteredClassifier/weka/classifiers/monotone/MinMaxExtension.java | 3,415 | /*
* MinMaxExtension.java
* Copyright (C) 2004 Stijn Lievens
*
*/ | block_comment | nl | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* MinMaxExtension.java
*<SUF>*/
package weka.classifiers.monotone;
import weka.classifiers.Classifier;
import weka.classifiers.monotone.util.InstancesUtil;
import weka.core.Capabilities;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import java.util.Enumeration;
import java.util.Vector;
/**
<!-- globalinfo-start -->
* This class is an implementation of the minimal and maximal extension.<br/>
* All attributes and the class are assumed to be ordinal. The order of the ordinal attributes is determined by the internal codes used by WEKA.<br/>
* <br/>
* Further information regarding these algorithms can be found in:<br/>
* <br/>
* S. Lievens, B. De Baets, K. Cao-Van (2006). A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting. Annals of Operations Research..<br/>
* <br/>
* Kim Cao-Van (2003). Supervised ranking: from semantics to algorithms.<br/>
* <br/>
* Stijn Lievens (2004). Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken.<br/>
* <br/>
* For more information about supervised ranking, see<br/>
* <br/>
* http://users.ugent.be/~slievens/supervised_ranking.php
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{Lievens2006,
* author = {S. Lievens and B. De Baets and K. Cao-Van},
* journal = {Annals of Operations Research},
* title = {A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting},
* year = {2006}
* }
*
* @phdthesis{Cao-Van2003,
* author = {Kim Cao-Van},
* school = {Ghent University},
* title = {Supervised ranking: from semantics to algorithms},
* year = {2003}
* }
*
* @mastersthesis{Lievens2004,
* author = {Stijn Lievens},
* school = {Ghent University},
* title = {Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken},
* year = {2004}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -M
* Use maximal extension (default: minimal extension)</pre>
*
<!-- options-end -->
*
* @author Stijn Lievens ([email protected])
* @version $Revision: 1.1 $
*/
public class MinMaxExtension
extends Classifier
implements TechnicalInformationHandler {
/** for serialization */
private static final long serialVersionUID = 8505830465540027104L;
/**
* The training instances.
*/
private Instances m_data;
/**
* parameter for choice between min extension and max extension
*/
private boolean m_min = true;
/**
* Returns a string describing the classifier.
* @return a description suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"This class is an implementation of the "
+ "minimal and maximal extension.\n"
+ "All attributes and the class are assumed to be ordinal. The order of "
+ "the ordinal attributes is determined by the internal codes used by "
+ "WEKA.\n\n"
+ "Further information regarding these algorithms can be found in:\n\n"
+ getTechnicalInformation().toString() + "\n\n"
+ "For more information about supervised ranking, see\n\n"
+ "http://users.ugent.be/~slievens/supervised_ranking.php";
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
TechnicalInformation additional;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "S. Lievens and B. De Baets and K. Cao-Van");
result.setValue(Field.YEAR, "2006");
result.setValue(Field.TITLE, "A Probabilistic Framework for the Design of Instance-Based Supervised Ranking Algorithms in an Ordinal Setting");
result.setValue(Field.JOURNAL, "Annals of Operations Research");
additional = result.add(Type.PHDTHESIS);
additional.setValue(Field.AUTHOR, "Kim Cao-Van");
additional.setValue(Field.YEAR, "2003");
additional.setValue(Field.TITLE, "Supervised ranking: from semantics to algorithms");
additional.setValue(Field.SCHOOL, "Ghent University");
additional = result.add(Type.MASTERSTHESIS);
additional.setValue(Field.AUTHOR, "Stijn Lievens");
additional.setValue(Field.YEAR, "2004");
additional.setValue(Field.TITLE, "Studie en implementatie van instantie-gebaseerde algoritmen voor gesuperviseerd rangschikken");
additional.setValue(Field.SCHOOL, "Ghent University");
return result;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Builds the classifier. This is in fact nothing else than copying
* the given instances.
*
* @param instances the training examples
* @throws Exception if the classifier is not able to handle the
* <code> instances </code>.
*/
public void buildClassifier(Instances instances) throws Exception {
getCapabilities().testWithFail(instances);
// copy the dataset
m_data = new Instances(instances);
// new dataset in which examples with missing class value are removed
m_data.deleteWithMissingClass();
}
/**
* Classifies the given instance.
*
* @param instance the instance to be classified
* @return a double representing the internal value
* of the label that is assigned to the given instance
*/
public double classifyInstance(Instance instance) {
double value;
if (m_min == true) {
value = 0;
for (int i = 0; i < m_data.numInstances(); i++) {
Instance i2 = m_data.instance(i);
if (InstancesUtil.smallerOrEqual(i2, instance) == true) {
value = Math.max(value, i2.classValue());
}
}
}
else {
value = m_data.classAttribute().numValues() - 1;
for (int i = 0; i < m_data.numInstances(); i++) {
Instance i2 = m_data.instance(i);
if (InstancesUtil.smallerOrEqual(instance, i2) == true) {
value = Math.min(value, i2.classValue());
}
}
}
return value;
}
/**
* After calling this method, the next classification will use the minimal
* extension.
*/
public void setMinExtension() {
m_min = true;
}
/**
* After calling this method, the next classification will use the maximal
* extension.
*/
public void setMaxExtension() {
m_min = false;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String minMaxExtensionTipText() {
return "If true, the minimal extension of the algorithm is chosen, "
+ "otherwise, it is the maximal extension";
}
/**
* Return if the minimal extension is in effect.
*
* @return <code> true </code> if the minimal is in effect,
* <code> false </code> otherwise
*/
public boolean getMinMaxExtension() {
return m_min;
}
/**
* Chooses between the minimal and maximal extension of the algorithm.
* If <code> min </code> is <code> true </code> then the minimal extension
* wil be in effect, otherwise it will the maximal extension.
*
* @param min do we choose the minimal extension
*/
public void setMinMaxExtension(boolean min) {
m_min = min;
}
/**
* Parses the options for this object. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -M
* Use maximal extension (default: minimal extension)</pre>
*
<!-- options-end -->
*
* @param options an array of strings containing the options for the classifier
* @throws Exception if
*/
public void setOptions(String[] options) throws Exception {
m_min = !Utils.getFlag('M',options); // check if -M option is present
super.setOptions(options);
}
/**
* Gets the current settings of this classifier.
*
* @return an array of strings suitable for passing to
* <code> setOptions </code>
*/
public String[] getOptions() {
int i;
Vector result;
String[] options;
result = new Vector();
options = super.getOptions();
for (i = 0; i < options.length; i++)
result.add(options[i]);
if (!m_min)
result.add("-M");
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Produces an enumeration describing the available options for
* this classifier.
*
* @return an enumeration with the available options.
*/
public Enumeration listOptions() {
Vector options = new Vector();
Enumeration enm = super.listOptions();
while (enm.hasMoreElements())
options.addElement(enm.nextElement());
String s = "\tUse maximal extension (default: minimal extension)";
options.add(new Option(s, "M", 0, "-M"));
return options.elements();
}
/**
* returns a string representation of this classifier
*
* @return the classname
*/
public String toString() {
return this.getClass().getName();
}
/**
* Main method for testing this class and for using it from the
* command line.
*
* @param args array of options for both the classifier <code>
* MinMaxExtension </code> and for <code> evaluateModel </code>
*/
public static void main(String[] args) {
runClassifier(new MinMaxExtension(), args);
}
}
|
103437_11 | // Name: Steve Regala
// USC NetID: sregala
// CSCI455 PA2
// Fall 2021
import java.util.ArrayList;
public class BookshelfTester {
public static void main(String[] args)
{
// EXERCISE 2:
// test constructor w/o input parameter & toString method
Bookshelf bookList1 = new Bookshelf();
System.out.println("TESTING constructor with no input parameter (bookList1) -->");
System.out.println("Expected: []");
System.out.println("Actual: " + bookList1.toString());
System.out.println();
// test constructor with input parameter & toString method
ArrayList<Integer> testArrayList = new ArrayList<Integer>();
testArrayList.add(2);
testArrayList.add(8);
testArrayList.add(10);
testArrayList.add(43);
testArrayList.add(21);
Bookshelf bookList2 = new Bookshelf(testArrayList);
System.out.println("TESTING constructor with input parameter (bookList2) -->");
System.out.println("Expected: [2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// EXERCISE 3
// test addFront(int height), addLast(int height), removeFront(), removeLast() ----
// addFront to an empty Bookshelf object
System.out.println("TESTING addFront -->");
System.out.println("Adding 54 and then 3 in front of bookList1..");
bookList1.addFront(54);
bookList1.addFront(3);
System.out.println("Expected: [3, 54]");
System.out.println("Actual: " + bookList1.toString());
// addFront to bookList2
System.out.println("Adding 500 in front of bookList2..");
bookList2.addFront(500);
System.out.println("Expected: [500, 2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// addLast to bookList1
System.out.println("TESTING addLast -->");
System.out.println("Adding 78 to the end of bookList1..");
bookList1.addLast(78);
System.out.println("Expected: [3, 54, 78]");
System.out.println("Actual: " + bookList1.toString());
System.out.println();
// removeFront() to bookList2
System.out.println("TESTING removeFront and that it prints what was removed -->");
System.out.println("Removing front of bookList2: " + bookList2.removeFront());
System.out.println("Expected: [2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// removeLast() to bookList2
System.out.println("TESTING removeLast and that it prints what was removed -->");
System.out.println("Removing last of bookList2: " + bookList2.removeLast());
System.out.println("Expected: [2, 8, 10, 43]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// EXERCISE 4
// test getHeight(int position), size(), isSorted() ----
// getHeight on bookList2
System.out.println("TESTING getHeight on bookList2: position 0 & position 2 -->");
System.out.println("Expected: 2");
System.out.println("Actual: " + bookList2.getHeight(0));
System.out.println("Expected: 10");
System.out.println("Actual: " + bookList2.getHeight(2));
System.out.println();
// size on bookList2
System.out.println("TESTING size on bookList2 -->");
System.out.println("Expected: 4");
System.out.println("Actual: " + bookList2.size());
System.out.println();
// isSorted on bookList1
System.out.println("TESTING isSorted on bookList1 after adding 6 at the end -->");
bookList1.addLast(6);
System.out.println("Expected: false");
System.out.println("Actual: " + bookList1.isSorted());
System.out.println();
// isSorted on bookList2
System.out.println("TESTING isSorted on bookList2 -->");
System.out.println("Expected: true");
System.out.println("Actual: " + bookList2.isSorted());
System.out.println();
// print the contents of bookList1 and bookList2
System.out.println("bookList1 object holds: " + bookList1.toString());
System.out.println("bookList2 object holds: " + bookList2.toString());
System.out.println();
// bookList1 -> [3, 54, 78, 6]
// bookList2 -> [2, 8, 10, 43, 21]
// ---------------------------------------------------------
// NOW TESTING ASSERT IMPLEMENTATION TEST
ArrayList<Integer> testArrayList2 = new ArrayList<Integer>();
testArrayList2.add(5);
testArrayList2.add(11);
testArrayList2.add(3);
Bookshelf bookList3 = new Bookshelf(testArrayList2);
System.out.println("bookList3 object holds: " + bookList3.toString());
// bookList3.addFront(-2);
/*
Exception in thread "main" java.lang.AssertionError
at Bookshelf.addFront(Bookshelf.java:67)
at BookshelfTester.main(BookshelfTester.java:123)
*/
//bookList3.addLast(-4);
/*
Exception in thread "main" java.lang.AssertionError
at Bookshelf.addLast(Bookshelf.java:80)
at BookshelfTester.main(BookshelfTester.java:130)
*/
/*
don't need to test remove with -ea because program will crash if
it includes a negative number or it when it tires to add a
negative number
remaining to be tested: removeFront, removeLast, getHeight, size, toString, isSorted
Follow-up question: would the assert statement be needed to all methods?
*/
}
} | svregala/Bookshelf_Keeper | BookshelfTester.java | 1,838 | // getHeight on bookList2 | line_comment | nl | // Name: Steve Regala
// USC NetID: sregala
// CSCI455 PA2
// Fall 2021
import java.util.ArrayList;
public class BookshelfTester {
public static void main(String[] args)
{
// EXERCISE 2:
// test constructor w/o input parameter & toString method
Bookshelf bookList1 = new Bookshelf();
System.out.println("TESTING constructor with no input parameter (bookList1) -->");
System.out.println("Expected: []");
System.out.println("Actual: " + bookList1.toString());
System.out.println();
// test constructor with input parameter & toString method
ArrayList<Integer> testArrayList = new ArrayList<Integer>();
testArrayList.add(2);
testArrayList.add(8);
testArrayList.add(10);
testArrayList.add(43);
testArrayList.add(21);
Bookshelf bookList2 = new Bookshelf(testArrayList);
System.out.println("TESTING constructor with input parameter (bookList2) -->");
System.out.println("Expected: [2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// EXERCISE 3
// test addFront(int height), addLast(int height), removeFront(), removeLast() ----
// addFront to an empty Bookshelf object
System.out.println("TESTING addFront -->");
System.out.println("Adding 54 and then 3 in front of bookList1..");
bookList1.addFront(54);
bookList1.addFront(3);
System.out.println("Expected: [3, 54]");
System.out.println("Actual: " + bookList1.toString());
// addFront to bookList2
System.out.println("Adding 500 in front of bookList2..");
bookList2.addFront(500);
System.out.println("Expected: [500, 2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// addLast to bookList1
System.out.println("TESTING addLast -->");
System.out.println("Adding 78 to the end of bookList1..");
bookList1.addLast(78);
System.out.println("Expected: [3, 54, 78]");
System.out.println("Actual: " + bookList1.toString());
System.out.println();
// removeFront() to bookList2
System.out.println("TESTING removeFront and that it prints what was removed -->");
System.out.println("Removing front of bookList2: " + bookList2.removeFront());
System.out.println("Expected: [2, 8, 10, 43, 21]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// removeLast() to bookList2
System.out.println("TESTING removeLast and that it prints what was removed -->");
System.out.println("Removing last of bookList2: " + bookList2.removeLast());
System.out.println("Expected: [2, 8, 10, 43]");
System.out.println("Actual: " + bookList2.toString());
System.out.println();
// EXERCISE 4
// test getHeight(int position), size(), isSorted() ----
// getHeight on<SUF>
System.out.println("TESTING getHeight on bookList2: position 0 & position 2 -->");
System.out.println("Expected: 2");
System.out.println("Actual: " + bookList2.getHeight(0));
System.out.println("Expected: 10");
System.out.println("Actual: " + bookList2.getHeight(2));
System.out.println();
// size on bookList2
System.out.println("TESTING size on bookList2 -->");
System.out.println("Expected: 4");
System.out.println("Actual: " + bookList2.size());
System.out.println();
// isSorted on bookList1
System.out.println("TESTING isSorted on bookList1 after adding 6 at the end -->");
bookList1.addLast(6);
System.out.println("Expected: false");
System.out.println("Actual: " + bookList1.isSorted());
System.out.println();
// isSorted on bookList2
System.out.println("TESTING isSorted on bookList2 -->");
System.out.println("Expected: true");
System.out.println("Actual: " + bookList2.isSorted());
System.out.println();
// print the contents of bookList1 and bookList2
System.out.println("bookList1 object holds: " + bookList1.toString());
System.out.println("bookList2 object holds: " + bookList2.toString());
System.out.println();
// bookList1 -> [3, 54, 78, 6]
// bookList2 -> [2, 8, 10, 43, 21]
// ---------------------------------------------------------
// NOW TESTING ASSERT IMPLEMENTATION TEST
ArrayList<Integer> testArrayList2 = new ArrayList<Integer>();
testArrayList2.add(5);
testArrayList2.add(11);
testArrayList2.add(3);
Bookshelf bookList3 = new Bookshelf(testArrayList2);
System.out.println("bookList3 object holds: " + bookList3.toString());
// bookList3.addFront(-2);
/*
Exception in thread "main" java.lang.AssertionError
at Bookshelf.addFront(Bookshelf.java:67)
at BookshelfTester.main(BookshelfTester.java:123)
*/
//bookList3.addLast(-4);
/*
Exception in thread "main" java.lang.AssertionError
at Bookshelf.addLast(Bookshelf.java:80)
at BookshelfTester.main(BookshelfTester.java:130)
*/
/*
don't need to test remove with -ea because program will crash if
it includes a negative number or it when it tires to add a
negative number
remaining to be tested: removeFront, removeLast, getHeight, size, toString, isSorted
Follow-up question: would the assert statement be needed to all methods?
*/
}
} |
30281_6 | package io.swagger.codegen.plugin;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.config.CodegenConfigurator;
/**
* Goal which generates client/server code from a swagger json/yaml definition.
*/
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true)
public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "verbose", required = false, defaultValue = "false")
private boolean verbose;
/**
* Client language to generate.
*/
@Parameter(name = "language", required = true)
private String language;
/**
* Location of the output directory.
*/
@Parameter(name = "output", property = "swagger.codegen.maven.plugin.output",
defaultValue = "${project.build.directory}/generated-sources/swagger")
private File output;
/**
* Location of the swagger spec, as URL or file.
*/
@Parameter(name = "inputSpec", required = true)
private String inputSpec;
/**
* Git user ID, e.g. swagger-api.
*/
@Parameter(name = "gitUserId", required = false)
private String gitUserId;
/**
* Git repo ID, e.g. swagger-codegen.
*/
@Parameter(name = "gitRepoId", required = false)
private String gitRepoId;
/**
* Folder containing the template files.
*/
@Parameter(name = "templateDirectory")
private File templateDirectory;
/**
* Adds authorization headers when fetching the swagger definitions remotely. " Pass in a
* URL-encoded string of name:header with a comma separating multiple values
*/
@Parameter(name = "auth")
private String auth;
/**
* Path to separate json configuration file.
*/
@Parameter(name = "configurationFile", required = false)
private String configurationFile;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name = "skipOverwrite", required = false)
private Boolean skipOverwrite;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name = "removeOperationIdPrefix", required = false)
private Boolean removeOperationIdPrefix;
/**
* The package to use for generated api objects/classes
*/
@Parameter(name = "apiPackage")
private String apiPackage;
/**
* The package to use for generated model objects/classes
*/
@Parameter(name = "modelPackage")
private String modelPackage;
/**
* The package to use for the generated invoker objects
*/
@Parameter(name = "invokerPackage")
private String invokerPackage;
/**
* groupId in generated pom.xml
*/
@Parameter(name = "groupId")
private String groupId;
/**
* artifactId in generated pom.xml
*/
@Parameter(name = "artifactId")
private String artifactId;
/**
* artifact version in generated pom.xml
*/
@Parameter(name = "artifactVersion")
private String artifactVersion;
/**
* Sets the library
*/
@Parameter(name = "library", required = false)
private String library;
/**
* Sets the prefix for model enums and classes
*/
@Parameter(name = "modelNamePrefix", required = false)
private String modelNamePrefix;
/**
* Sets the suffix for model enums and classes
*/
@Parameter(name = "modelNameSuffix", required = false)
private String modelNameSuffix;
/**
* Adds a prefix for all generated local variables
*/
@Parameter(name = "localVariablePrefix", required = false)
private String localVariablePrefix;
/**
* Sets an optional ignoreFileOverride path
*/
@Parameter(name = "ignoreFileOverride", required = false)
private String ignoreFileOverride;
/**
* A map of language-specific parameters as passed with the -c option to the command line
*/
@Parameter(name = "configOptions")
private Map<?, ?> configOptions;
/**
* A map of types and the types they should be instantiated as
*/
@Parameter(name = "instantiationTypes")
private List<String> instantiationTypes;
/**
* A map of classes and the import that should be used for that class
*/
@Parameter(name = "importMappings")
private List<String> importMappings;
/**
* A map of swagger spec types and the generated code types to use for them
*/
@Parameter(name = "typeMappings")
private List<String> typeMappings;
/**
* A map of additional language specific primitive types
*/
@Parameter(name = "languageSpecificPrimitives")
private List<String> languageSpecificPrimitives;
/**
* A map of additional properties that can be referenced by the mustache templates
* <additionalProperties>
* <additionalProperty>key=value</additionalProperty>
* </additionalProperties>
*/
@Parameter(name = "additionalProperties")
private List<String> additionalProperties;
/**
* A map of reserved names and how they should be escaped
*/
@Parameter(name = "reservedWordsMappings")
private List<String> reservedWordsMappings;
/**
* Generate the apis
*/
@Parameter(name = "generateApis", required = false)
private Boolean generateApis = true;
/**
* Generate the models
*/
@Parameter(name = "generateModels", required = false)
private Boolean generateModels = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "modelsToGenerate", required = false)
private String modelsToGenerate = "";
/**
* Generate the supporting files
*/
@Parameter(name = "generateSupportingFiles", required = false)
private Boolean generateSupportingFiles = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "supportingFilesToGenerate", required = false)
private String supportingFilesToGenerate = "";
/**
* Generate the model tests
*/
@Parameter(name = "generateModelTests", required = false)
private Boolean generateModelTests = true;
/**
* Generate the model documentation
*/
@Parameter(name = "generateModelDocumentation", required = false)
private Boolean generateModelDocumentation = true;
/**
* Generate the api tests
*/
@Parameter(name = "generateApiTests", required = false)
private Boolean generateApiTests = true;
/**
* Generate the api documentation
*/
@Parameter(name = "generateApiDocumentation", required = false)
private Boolean generateApiDocumentation = true;
/**
* Generate the api documentation
*/
@Parameter(name = "withXml", required = false)
private Boolean withXml = false;
/**
* Skip the execution.
*/
@Parameter(name = "skip", property = "codegen.skip", required = false, defaultValue = "false")
private Boolean skip;
/**
* Add the output directory to the project as a source root, so that the generated java types
* are compiled and included in the project artifact.
*/
@Parameter(defaultValue = "true")
private boolean addCompileSourceRoot = true;
@Parameter
protected Map<String, String> environmentVariables = new HashMap<String, String>();
@Parameter
protected Map<String, String> originalEnvironmentVariables = new HashMap<String, String>();
@Parameter
private boolean configHelp = false;
/**
* The project being built.
*/
@Parameter(readonly = true, required = true, defaultValue = "${project}")
private MavenProject project;
@Override
public void execute() throws MojoExecutionException {
// Using the naive approach for achieving thread safety
synchronized (CodeGenMojo.class) {
execute_();
}
}
protected void execute_() throws MojoExecutionException {
if (skip) {
getLog().info("Code generation is skipped.");
// Even when no new sources are generated, the existing ones should
// still be compiled if needed.
addCompileSourceRootIfConfigured();
return;
}
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);
// if a config file wasn't specified or we were unable to read it
if (configurator == null) {
configurator = new CodegenConfigurator();
}
configurator.setVerbose(verbose);
if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
if (isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(ignoreFileOverride)) {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
configurator.setLang(language);
configurator.setOutputDir(output.getAbsolutePath());
if (isNotEmpty(auth)) {
configurator.setAuth(auth);
}
if (isNotEmpty(apiPackage)) {
configurator.setApiPackage(apiPackage);
}
if (isNotEmpty(modelPackage)) {
configurator.setModelPackage(modelPackage);
}
if (isNotEmpty(invokerPackage)) {
configurator.setInvokerPackage(invokerPackage);
}
if (isNotEmpty(groupId)) {
configurator.setGroupId(groupId);
}
if (isNotEmpty(artifactId)) {
configurator.setArtifactId(artifactId);
}
if (isNotEmpty(artifactVersion)) {
configurator.setArtifactVersion(artifactVersion);
}
if (isNotEmpty(library)) {
configurator.setLibrary(library);
}
if (isNotEmpty(modelNamePrefix)) {
configurator.setModelNamePrefix(modelNamePrefix);
}
if (isNotEmpty(modelNameSuffix)) {
configurator.setModelNameSuffix(modelNameSuffix);
}
if (isNotEmpty(localVariablePrefix)) {
configurator.setLocalVariablePrefix(localVariablePrefix);
}
if (null != templateDirectory) {
configurator.setTemplateDir(templateDirectory.getAbsolutePath());
}
// Set generation options
if (null != generateApis && generateApis) {
System.setProperty(CodegenConstants.APIS, "");
} else {
System.clearProperty(CodegenConstants.APIS);
}
if (null != generateModels && generateModels) {
System.setProperty(CodegenConstants.MODELS, modelsToGenerate);
} else {
System.clearProperty(CodegenConstants.MODELS);
}
if (null != generateSupportingFiles && generateSupportingFiles) {
System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate);
} else {
System.clearProperty(CodegenConstants.SUPPORTING_FILES);
}
System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString());
System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString());
System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString());
System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString());
System.setProperty(CodegenConstants.WITH_XML, withXml.toString());
if (configOptions != null) {
// Retained for backwards-compataibility with configOptions -> instantiation-types
if (instantiationTypes == null && configOptions.containsKey("instantiation-types")) {
applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> import-mappings
if (importMappings == null && configOptions.containsKey("import-mappings")) {
applyImportMappingsKvp(configOptions.get("import-mappings").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> type-mappings
if (typeMappings == null && configOptions.containsKey("type-mappings")) {
applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> language-specific-primitives
if (languageSpecificPrimitives == null && configOptions.containsKey("language-specific-primitives")) {
applyLanguageSpecificPrimitivesCsv(configOptions
.get("language-specific-primitives").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> additional-properties
if (additionalProperties == null && configOptions.containsKey("additional-properties")) {
applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> reserved-words-mappings
if (reservedWordsMappings == null && configOptions.containsKey("reserved-words-mappings")) {
applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings")
.toString(), configurator);
}
}
//Apply Instantiation Types
if (instantiationTypes != null && (configOptions == null || !configOptions.containsKey("instantiation-types"))) {
applyInstantiationTypesKvpList(instantiationTypes, configurator);
}
//Apply Import Mappings
if (importMappings != null && (configOptions == null || !configOptions.containsKey("import-mappings"))) {
applyImportMappingsKvpList(importMappings, configurator);
}
//Apply Type Mappings
if (typeMappings != null && (configOptions == null || !configOptions.containsKey("type-mappings"))) {
applyTypeMappingsKvpList(typeMappings, configurator);
}
//Apply Language Specific Primitives
if (languageSpecificPrimitives != null && (configOptions == null || !configOptions.containsKey("language-specific-primitives"))) {
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
}
//Apply Additional Properties
if (additionalProperties != null && (configOptions == null || !configOptions.containsKey("additional-properties"))) {
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
}
//Apply Reserved Words Mappings
if (reservedWordsMappings != null && (configOptions == null || !configOptions.containsKey("reserved-words-mappings"))) {
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
}
if (environmentVariables != null) {
for (String key : environmentVariables.keySet()) {
originalEnvironmentVariables.put(key, System.getProperty(key));
String value = environmentVariables.get(key);
if (value == null) {
// don't put null values
value = "";
}
System.setProperty(key, value);
configurator.addSystemProperty(key, value);
}
}
final ClientOptInput input = configurator.toClientOptInput();
final CodegenConfig config = input.getConfig();
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
input.getConfig().additionalProperties()
.put(langCliOption.getOpt(), configOptions.get(langCliOption.getOpt()));
}
}
}
if (configHelp) {
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t "
+ langCliOption.getOptionHelp().replaceAll("\n", "\n\t "));
System.out.println();
}
return;
}
try {
new DefaultGenerator().opts(input).generate();
} catch (Exception e) {
// Maven logs exceptions thrown by plugins only if invoked with -e
// I find it annoying to jump through hoops to get basic diagnostic information,
// so let's log it in any case:
getLog().error(e);
throw new MojoExecutionException(
"Code generation failed. See above for the full exception.");
}
addCompileSourceRootIfConfigured();
}
private void addCompileSourceRootIfConfigured() {
if (addCompileSourceRoot) {
final Object sourceFolderObject =
configOptions == null ? null : configOptions
.get(CodegenConstants.SOURCE_FOLDER);
final String sourceFolder =
sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString();
String sourceJavaFolder = output.toString() + "/" + sourceFolder;
project.addCompileSourceRoot(sourceJavaFolder);
}
// Reset all environment variables to their original value. This prevents unexpected
// behaviour
// when running the plugin multiple consecutive times with different configurations.
for (Map.Entry<String, String> entry : originalEnvironmentVariables.entrySet()) {
if (entry.getValue() == null) {
System.clearProperty(entry.getKey());
} else {
System.setProperty(entry.getKey(), entry.getValue());
}
}
}
}
| swagger-api/swagger-codegen | modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java | 5,383 | /**
* Git repo ID, e.g. swagger-codegen.
*/ | block_comment | nl | package io.swagger.codegen.plugin;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.config.CodegenConfigurator;
/**
* Goal which generates client/server code from a swagger json/yaml definition.
*/
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true)
public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "verbose", required = false, defaultValue = "false")
private boolean verbose;
/**
* Client language to generate.
*/
@Parameter(name = "language", required = true)
private String language;
/**
* Location of the output directory.
*/
@Parameter(name = "output", property = "swagger.codegen.maven.plugin.output",
defaultValue = "${project.build.directory}/generated-sources/swagger")
private File output;
/**
* Location of the swagger spec, as URL or file.
*/
@Parameter(name = "inputSpec", required = true)
private String inputSpec;
/**
* Git user ID, e.g. swagger-api.
*/
@Parameter(name = "gitUserId", required = false)
private String gitUserId;
/**
* Git repo ID,<SUF>*/
@Parameter(name = "gitRepoId", required = false)
private String gitRepoId;
/**
* Folder containing the template files.
*/
@Parameter(name = "templateDirectory")
private File templateDirectory;
/**
* Adds authorization headers when fetching the swagger definitions remotely. " Pass in a
* URL-encoded string of name:header with a comma separating multiple values
*/
@Parameter(name = "auth")
private String auth;
/**
* Path to separate json configuration file.
*/
@Parameter(name = "configurationFile", required = false)
private String configurationFile;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name = "skipOverwrite", required = false)
private Boolean skipOverwrite;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name = "removeOperationIdPrefix", required = false)
private Boolean removeOperationIdPrefix;
/**
* The package to use for generated api objects/classes
*/
@Parameter(name = "apiPackage")
private String apiPackage;
/**
* The package to use for generated model objects/classes
*/
@Parameter(name = "modelPackage")
private String modelPackage;
/**
* The package to use for the generated invoker objects
*/
@Parameter(name = "invokerPackage")
private String invokerPackage;
/**
* groupId in generated pom.xml
*/
@Parameter(name = "groupId")
private String groupId;
/**
* artifactId in generated pom.xml
*/
@Parameter(name = "artifactId")
private String artifactId;
/**
* artifact version in generated pom.xml
*/
@Parameter(name = "artifactVersion")
private String artifactVersion;
/**
* Sets the library
*/
@Parameter(name = "library", required = false)
private String library;
/**
* Sets the prefix for model enums and classes
*/
@Parameter(name = "modelNamePrefix", required = false)
private String modelNamePrefix;
/**
* Sets the suffix for model enums and classes
*/
@Parameter(name = "modelNameSuffix", required = false)
private String modelNameSuffix;
/**
* Adds a prefix for all generated local variables
*/
@Parameter(name = "localVariablePrefix", required = false)
private String localVariablePrefix;
/**
* Sets an optional ignoreFileOverride path
*/
@Parameter(name = "ignoreFileOverride", required = false)
private String ignoreFileOverride;
/**
* A map of language-specific parameters as passed with the -c option to the command line
*/
@Parameter(name = "configOptions")
private Map<?, ?> configOptions;
/**
* A map of types and the types they should be instantiated as
*/
@Parameter(name = "instantiationTypes")
private List<String> instantiationTypes;
/**
* A map of classes and the import that should be used for that class
*/
@Parameter(name = "importMappings")
private List<String> importMappings;
/**
* A map of swagger spec types and the generated code types to use for them
*/
@Parameter(name = "typeMappings")
private List<String> typeMappings;
/**
* A map of additional language specific primitive types
*/
@Parameter(name = "languageSpecificPrimitives")
private List<String> languageSpecificPrimitives;
/**
* A map of additional properties that can be referenced by the mustache templates
* <additionalProperties>
* <additionalProperty>key=value</additionalProperty>
* </additionalProperties>
*/
@Parameter(name = "additionalProperties")
private List<String> additionalProperties;
/**
* A map of reserved names and how they should be escaped
*/
@Parameter(name = "reservedWordsMappings")
private List<String> reservedWordsMappings;
/**
* Generate the apis
*/
@Parameter(name = "generateApis", required = false)
private Boolean generateApis = true;
/**
* Generate the models
*/
@Parameter(name = "generateModels", required = false)
private Boolean generateModels = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "modelsToGenerate", required = false)
private String modelsToGenerate = "";
/**
* Generate the supporting files
*/
@Parameter(name = "generateSupportingFiles", required = false)
private Boolean generateSupportingFiles = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "supportingFilesToGenerate", required = false)
private String supportingFilesToGenerate = "";
/**
* Generate the model tests
*/
@Parameter(name = "generateModelTests", required = false)
private Boolean generateModelTests = true;
/**
* Generate the model documentation
*/
@Parameter(name = "generateModelDocumentation", required = false)
private Boolean generateModelDocumentation = true;
/**
* Generate the api tests
*/
@Parameter(name = "generateApiTests", required = false)
private Boolean generateApiTests = true;
/**
* Generate the api documentation
*/
@Parameter(name = "generateApiDocumentation", required = false)
private Boolean generateApiDocumentation = true;
/**
* Generate the api documentation
*/
@Parameter(name = "withXml", required = false)
private Boolean withXml = false;
/**
* Skip the execution.
*/
@Parameter(name = "skip", property = "codegen.skip", required = false, defaultValue = "false")
private Boolean skip;
/**
* Add the output directory to the project as a source root, so that the generated java types
* are compiled and included in the project artifact.
*/
@Parameter(defaultValue = "true")
private boolean addCompileSourceRoot = true;
@Parameter
protected Map<String, String> environmentVariables = new HashMap<String, String>();
@Parameter
protected Map<String, String> originalEnvironmentVariables = new HashMap<String, String>();
@Parameter
private boolean configHelp = false;
/**
* The project being built.
*/
@Parameter(readonly = true, required = true, defaultValue = "${project}")
private MavenProject project;
@Override
public void execute() throws MojoExecutionException {
// Using the naive approach for achieving thread safety
synchronized (CodeGenMojo.class) {
execute_();
}
}
protected void execute_() throws MojoExecutionException {
if (skip) {
getLog().info("Code generation is skipped.");
// Even when no new sources are generated, the existing ones should
// still be compiled if needed.
addCompileSourceRootIfConfigured();
return;
}
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);
// if a config file wasn't specified or we were unable to read it
if (configurator == null) {
configurator = new CodegenConfigurator();
}
configurator.setVerbose(verbose);
if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
if (isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(ignoreFileOverride)) {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
configurator.setLang(language);
configurator.setOutputDir(output.getAbsolutePath());
if (isNotEmpty(auth)) {
configurator.setAuth(auth);
}
if (isNotEmpty(apiPackage)) {
configurator.setApiPackage(apiPackage);
}
if (isNotEmpty(modelPackage)) {
configurator.setModelPackage(modelPackage);
}
if (isNotEmpty(invokerPackage)) {
configurator.setInvokerPackage(invokerPackage);
}
if (isNotEmpty(groupId)) {
configurator.setGroupId(groupId);
}
if (isNotEmpty(artifactId)) {
configurator.setArtifactId(artifactId);
}
if (isNotEmpty(artifactVersion)) {
configurator.setArtifactVersion(artifactVersion);
}
if (isNotEmpty(library)) {
configurator.setLibrary(library);
}
if (isNotEmpty(modelNamePrefix)) {
configurator.setModelNamePrefix(modelNamePrefix);
}
if (isNotEmpty(modelNameSuffix)) {
configurator.setModelNameSuffix(modelNameSuffix);
}
if (isNotEmpty(localVariablePrefix)) {
configurator.setLocalVariablePrefix(localVariablePrefix);
}
if (null != templateDirectory) {
configurator.setTemplateDir(templateDirectory.getAbsolutePath());
}
// Set generation options
if (null != generateApis && generateApis) {
System.setProperty(CodegenConstants.APIS, "");
} else {
System.clearProperty(CodegenConstants.APIS);
}
if (null != generateModels && generateModels) {
System.setProperty(CodegenConstants.MODELS, modelsToGenerate);
} else {
System.clearProperty(CodegenConstants.MODELS);
}
if (null != generateSupportingFiles && generateSupportingFiles) {
System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate);
} else {
System.clearProperty(CodegenConstants.SUPPORTING_FILES);
}
System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString());
System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString());
System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString());
System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString());
System.setProperty(CodegenConstants.WITH_XML, withXml.toString());
if (configOptions != null) {
// Retained for backwards-compataibility with configOptions -> instantiation-types
if (instantiationTypes == null && configOptions.containsKey("instantiation-types")) {
applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> import-mappings
if (importMappings == null && configOptions.containsKey("import-mappings")) {
applyImportMappingsKvp(configOptions.get("import-mappings").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> type-mappings
if (typeMappings == null && configOptions.containsKey("type-mappings")) {
applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> language-specific-primitives
if (languageSpecificPrimitives == null && configOptions.containsKey("language-specific-primitives")) {
applyLanguageSpecificPrimitivesCsv(configOptions
.get("language-specific-primitives").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> additional-properties
if (additionalProperties == null && configOptions.containsKey("additional-properties")) {
applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> reserved-words-mappings
if (reservedWordsMappings == null && configOptions.containsKey("reserved-words-mappings")) {
applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings")
.toString(), configurator);
}
}
//Apply Instantiation Types
if (instantiationTypes != null && (configOptions == null || !configOptions.containsKey("instantiation-types"))) {
applyInstantiationTypesKvpList(instantiationTypes, configurator);
}
//Apply Import Mappings
if (importMappings != null && (configOptions == null || !configOptions.containsKey("import-mappings"))) {
applyImportMappingsKvpList(importMappings, configurator);
}
//Apply Type Mappings
if (typeMappings != null && (configOptions == null || !configOptions.containsKey("type-mappings"))) {
applyTypeMappingsKvpList(typeMappings, configurator);
}
//Apply Language Specific Primitives
if (languageSpecificPrimitives != null && (configOptions == null || !configOptions.containsKey("language-specific-primitives"))) {
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
}
//Apply Additional Properties
if (additionalProperties != null && (configOptions == null || !configOptions.containsKey("additional-properties"))) {
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
}
//Apply Reserved Words Mappings
if (reservedWordsMappings != null && (configOptions == null || !configOptions.containsKey("reserved-words-mappings"))) {
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
}
if (environmentVariables != null) {
for (String key : environmentVariables.keySet()) {
originalEnvironmentVariables.put(key, System.getProperty(key));
String value = environmentVariables.get(key);
if (value == null) {
// don't put null values
value = "";
}
System.setProperty(key, value);
configurator.addSystemProperty(key, value);
}
}
final ClientOptInput input = configurator.toClientOptInput();
final CodegenConfig config = input.getConfig();
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
input.getConfig().additionalProperties()
.put(langCliOption.getOpt(), configOptions.get(langCliOption.getOpt()));
}
}
}
if (configHelp) {
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t "
+ langCliOption.getOptionHelp().replaceAll("\n", "\n\t "));
System.out.println();
}
return;
}
try {
new DefaultGenerator().opts(input).generate();
} catch (Exception e) {
// Maven logs exceptions thrown by plugins only if invoked with -e
// I find it annoying to jump through hoops to get basic diagnostic information,
// so let's log it in any case:
getLog().error(e);
throw new MojoExecutionException(
"Code generation failed. See above for the full exception.");
}
addCompileSourceRootIfConfigured();
}
private void addCompileSourceRootIfConfigured() {
if (addCompileSourceRoot) {
final Object sourceFolderObject =
configOptions == null ? null : configOptions
.get(CodegenConstants.SOURCE_FOLDER);
final String sourceFolder =
sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString();
String sourceJavaFolder = output.toString() + "/" + sourceFolder;
project.addCompileSourceRoot(sourceJavaFolder);
}
// Reset all environment variables to their original value. This prevents unexpected
// behaviour
// when running the plugin multiple consecutive times with different configurations.
for (Map.Entry<String, String> entry : originalEnvironmentVariables.entrySet()) {
if (entry.getValue() == null) {
System.clearProperty(entry.getKey());
} else {
System.setProperty(entry.getKey(), entry.getValue());
}
}
}
}
|
83443_9 | /**
*/
package org.hl7.cdsdt.r2;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Entity Name Part Qualifier</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The qualifier is a set of codes each of which specifies a certain subcategory of the name part in addition to the main name part type. For example, a given name may be flagged as a nickname, a family name may be a pseudonym or a name of public records.
*
* CodeSystem "EntityNamePartTypeQualifierR2", OID: 2.16.840.1.113883.5.1122, Owner: HL7
* <!-- end-model-doc -->
* @see org.hl7.cdsdt.r2.R2Package#getEntityNamePartQualifier()
* @model extendedMetaData="name='EntityNamePartQualifier'"
* @generated
*/
public enum EntityNamePartQualifier implements Enumerator {
/**
* The '<em><b>LS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LS_VALUE
* @generated
* @ordered
*/
LS(0, "LS", "LS"),
/**
* The '<em><b>AC</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #AC_VALUE
* @generated
* @ordered
*/
AC(1, "AC", "AC"),
/**
* The '<em><b>NB</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NB_VALUE
* @generated
* @ordered
*/
NB(2, "NB", "NB"),
/**
* The '<em><b>PR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PR_VALUE
* @generated
* @ordered
*/
PR(3, "PR", "PR"),
/**
* The '<em><b>HON</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #HON_VALUE
* @generated
* @ordered
*/
HON(4, "HON", "HON"),
/**
* The '<em><b>BR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #BR_VALUE
* @generated
* @ordered
*/
BR(5, "BR", "BR"),
/**
* The '<em><b>AD</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #AD_VALUE
* @generated
* @ordered
*/
AD(6, "AD", "AD"),
/**
* The '<em><b>SP</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SP_VALUE
* @generated
* @ordered
*/
SP(7, "SP", "SP"),
/**
* The '<em><b>MID</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #MID_VALUE
* @generated
* @ordered
*/
MID(8, "MID", "MID"),
/**
* The '<em><b>CL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CL_VALUE
* @generated
* @ordered
*/
CL(9, "CL", "CL"),
/**
* The '<em><b>IN</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #IN_VALUE
* @generated
* @ordered
*/
IN(10, "IN", "IN"),
/**
* The '<em><b>PFX</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PFX_VALUE
* @generated
* @ordered
*/
PFX(11, "PFX", "PFX"),
/**
* The '<em><b>SFX</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SFX_VALUE
* @generated
* @ordered
*/
SFX(12, "SFX", "SFX");
/**
* The '<em><b>LS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Legal Status : For organizations a suffix indicating the legal status, e.g., "Inc.", "Co.", "AG", "GmbH", "B.V." "S.A.", "Ltd." Etc.
* <!-- end-model-doc -->
* @see #LS
* @model
* @generated
* @ordered
*/
public static final int LS_VALUE = 0;
/**
* The '<em><b>AC</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Academic : Indicates that a prefix like "Dr." or a suffix like "M.D." or "Ph.D." is an academic title
* <!-- end-model-doc -->
* @see #AC
* @model
* @generated
* @ordered
*/
public static final int AC_VALUE = 1;
/**
* The '<em><b>NB</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Nobility : In Europe and Asia, there are still people with nobility titles (aristocrats). German "von" is generally a nobility title, not a mere voorvoegsel. Others are "Earl of" or "His Majesty King of..." etc. Rarely used nowadays, but some systems do keep track of this
* <!-- end-model-doc -->
* @see #NB
* @model
* @generated
* @ordered
*/
public static final int NB_VALUE = 2;
/**
* The '<em><b>PR</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Professional : Primarily in the British Imperial culture people tend to have an abbreviation of their professional organization as part of their credential suffices
* <!-- end-model-doc -->
* @see #PR
* @model
* @generated
* @ordered
*/
public static final int PR_VALUE = 3;
/**
* The '<em><b>HON</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Honorific : A honorific such as "The Right Honourable" or "Weledelgeleerde Heer".
* <!-- end-model-doc -->
* @see #HON
* @model
* @generated
* @ordered
*/
public static final int HON_VALUE = 4;
/**
* The '<em><b>BR</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Birth : A name that a person was given at birth or established as a consequence of adoption.
*
* Note: this is not used for temporary names assigned at birth such as "Baby of Smith" - which is just a name with a use code of "TEMP".
* <!-- end-model-doc -->
* @see #BR
* @model
* @generated
* @ordered
*/
public static final int BR_VALUE = 5;
/**
* The '<em><b>AD</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Acquired : A name part a person acquired.
*
* The name part may be acquired by adoption, or the person may have chosen to use the name part for some other reason.
*
* Note: this differs from an Other/Psuedonym/Alias in that an acquired name part is acquired on a formal basis rather than an informal one (e.g. registered as part of the official name)
* <!-- end-model-doc -->
* @see #AD
* @model
* @generated
* @ordered
*/
public static final int AD_VALUE = 6;
/**
* The '<em><b>SP</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Spouse : The name assumed from the partner in a marital relationship. Usually the spouse's family name. Note that no inference about gender can be made from the existence of spouse names
* <!-- end-model-doc -->
* @see #SP
* @model
* @generated
* @ordered
*/
public static final int SP_VALUE = 7;
/**
* The '<em><b>MID</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Middle Name : Indicates that the name part is a middle name.
* Usage Notes:
* In general, the english 'middle name' concept is all of the given names after the first. This qualifier may be used to explicitly indicate which given names are considered to be middle names.
* The middle name qualifier may also be used with family names. This is a Scandinavian use case, matching the concept of "mellomnavn" / "mellannamn". Note that there are specific rules that indicate what names may be taken as a mellannamn in different Scandinavian countries
* <!-- end-model-doc -->
* @see #MID
* @model
* @generated
* @ordered
*/
public static final int MID_VALUE = 8;
/**
* The '<em><b>CL</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Callme : Callme is used to indicate which of the various name parts is used when interacting with the person
* <!-- end-model-doc -->
* @see #CL
* @model
* @generated
* @ordered
*/
public static final int CL_VALUE = 9;
/**
* The '<em><b>IN</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Initial : Indicates that a name part is just an initial. Initials do not imply a trailing period since this would not work with non-Latin scripts. Initials may consist of more than one letter, e.g., "Ph." could stand for "Philippe" or "Th." for "Thomas"
* <!-- end-model-doc -->
* @see #IN
* @model
* @generated
* @ordered
*/
public static final int IN_VALUE = 10;
/**
* The '<em><b>PFX</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Prefix : A prefix has a strong association to the immediately following name part. A prefix has no implicit trailing white space (it has implicit leading white space though).
* <!-- end-model-doc -->
* @see #PFX
* @model
* @generated
* @ordered
*/
public static final int PFX_VALUE = 11;
/**
* The '<em><b>SFX</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Suffix : A suffix has a strong association to the immediately preceding name part. A suffix has no implicit leading white space (it has implicit trailing white space though).
* <!-- end-model-doc -->
* @see #SFX
* @model
* @generated
* @ordered
*/
public static final int SFX_VALUE = 12;
/**
* An array of all the '<em><b>Entity Name Part Qualifier</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final EntityNamePartQualifier[] VALUES_ARRAY =
new EntityNamePartQualifier[] {
LS,
AC,
NB,
PR,
HON,
BR,
AD,
SP,
MID,
CL,
IN,
PFX,
SFX,
};
/**
* A public read-only list of all the '<em><b>Entity Name Part Qualifier</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<EntityNamePartQualifier> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
EntityNamePartQualifier result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
EntityNamePartQualifier result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier get(int value) {
switch (value) {
case LS_VALUE: return LS;
case AC_VALUE: return AC;
case NB_VALUE: return NB;
case PR_VALUE: return PR;
case HON_VALUE: return HON;
case BR_VALUE: return BR;
case AD_VALUE: return AD;
case SP_VALUE: return SP;
case MID_VALUE: return MID;
case CL_VALUE: return CL;
case IN_VALUE: return IN;
case PFX_VALUE: return PFX;
case SFX_VALUE: return SFX;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EntityNamePartQualifier(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //EntityNamePartQualifier
| swmuir/knarts | knarts/plugins/org.hl7.knart.core/src/org/hl7/cdsdt/r2/EntityNamePartQualifier.java | 4,594 | /**
* The '<em><b>MID</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #MID_VALUE
* @generated
* @ordered
*/ | block_comment | nl | /**
*/
package org.hl7.cdsdt.r2;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Entity Name Part Qualifier</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The qualifier is a set of codes each of which specifies a certain subcategory of the name part in addition to the main name part type. For example, a given name may be flagged as a nickname, a family name may be a pseudonym or a name of public records.
*
* CodeSystem "EntityNamePartTypeQualifierR2", OID: 2.16.840.1.113883.5.1122, Owner: HL7
* <!-- end-model-doc -->
* @see org.hl7.cdsdt.r2.R2Package#getEntityNamePartQualifier()
* @model extendedMetaData="name='EntityNamePartQualifier'"
* @generated
*/
public enum EntityNamePartQualifier implements Enumerator {
/**
* The '<em><b>LS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LS_VALUE
* @generated
* @ordered
*/
LS(0, "LS", "LS"),
/**
* The '<em><b>AC</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #AC_VALUE
* @generated
* @ordered
*/
AC(1, "AC", "AC"),
/**
* The '<em><b>NB</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NB_VALUE
* @generated
* @ordered
*/
NB(2, "NB", "NB"),
/**
* The '<em><b>PR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PR_VALUE
* @generated
* @ordered
*/
PR(3, "PR", "PR"),
/**
* The '<em><b>HON</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #HON_VALUE
* @generated
* @ordered
*/
HON(4, "HON", "HON"),
/**
* The '<em><b>BR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #BR_VALUE
* @generated
* @ordered
*/
BR(5, "BR", "BR"),
/**
* The '<em><b>AD</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #AD_VALUE
* @generated
* @ordered
*/
AD(6, "AD", "AD"),
/**
* The '<em><b>SP</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SP_VALUE
* @generated
* @ordered
*/
SP(7, "SP", "SP"),
/**
* The '<em><b>MID</b></em>' literal<SUF>*/
MID(8, "MID", "MID"),
/**
* The '<em><b>CL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CL_VALUE
* @generated
* @ordered
*/
CL(9, "CL", "CL"),
/**
* The '<em><b>IN</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #IN_VALUE
* @generated
* @ordered
*/
IN(10, "IN", "IN"),
/**
* The '<em><b>PFX</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PFX_VALUE
* @generated
* @ordered
*/
PFX(11, "PFX", "PFX"),
/**
* The '<em><b>SFX</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SFX_VALUE
* @generated
* @ordered
*/
SFX(12, "SFX", "SFX");
/**
* The '<em><b>LS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Legal Status : For organizations a suffix indicating the legal status, e.g., "Inc.", "Co.", "AG", "GmbH", "B.V." "S.A.", "Ltd." Etc.
* <!-- end-model-doc -->
* @see #LS
* @model
* @generated
* @ordered
*/
public static final int LS_VALUE = 0;
/**
* The '<em><b>AC</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Academic : Indicates that a prefix like "Dr." or a suffix like "M.D." or "Ph.D." is an academic title
* <!-- end-model-doc -->
* @see #AC
* @model
* @generated
* @ordered
*/
public static final int AC_VALUE = 1;
/**
* The '<em><b>NB</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Nobility : In Europe and Asia, there are still people with nobility titles (aristocrats). German "von" is generally a nobility title, not a mere voorvoegsel. Others are "Earl of" or "His Majesty King of..." etc. Rarely used nowadays, but some systems do keep track of this
* <!-- end-model-doc -->
* @see #NB
* @model
* @generated
* @ordered
*/
public static final int NB_VALUE = 2;
/**
* The '<em><b>PR</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Professional : Primarily in the British Imperial culture people tend to have an abbreviation of their professional organization as part of their credential suffices
* <!-- end-model-doc -->
* @see #PR
* @model
* @generated
* @ordered
*/
public static final int PR_VALUE = 3;
/**
* The '<em><b>HON</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Honorific : A honorific such as "The Right Honourable" or "Weledelgeleerde Heer".
* <!-- end-model-doc -->
* @see #HON
* @model
* @generated
* @ordered
*/
public static final int HON_VALUE = 4;
/**
* The '<em><b>BR</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Birth : A name that a person was given at birth or established as a consequence of adoption.
*
* Note: this is not used for temporary names assigned at birth such as "Baby of Smith" - which is just a name with a use code of "TEMP".
* <!-- end-model-doc -->
* @see #BR
* @model
* @generated
* @ordered
*/
public static final int BR_VALUE = 5;
/**
* The '<em><b>AD</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Acquired : A name part a person acquired.
*
* The name part may be acquired by adoption, or the person may have chosen to use the name part for some other reason.
*
* Note: this differs from an Other/Psuedonym/Alias in that an acquired name part is acquired on a formal basis rather than an informal one (e.g. registered as part of the official name)
* <!-- end-model-doc -->
* @see #AD
* @model
* @generated
* @ordered
*/
public static final int AD_VALUE = 6;
/**
* The '<em><b>SP</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Spouse : The name assumed from the partner in a marital relationship. Usually the spouse's family name. Note that no inference about gender can be made from the existence of spouse names
* <!-- end-model-doc -->
* @see #SP
* @model
* @generated
* @ordered
*/
public static final int SP_VALUE = 7;
/**
* The '<em><b>MID</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Middle Name : Indicates that the name part is a middle name.
* Usage Notes:
* In general, the english 'middle name' concept is all of the given names after the first. This qualifier may be used to explicitly indicate which given names are considered to be middle names.
* The middle name qualifier may also be used with family names. This is a Scandinavian use case, matching the concept of "mellomnavn" / "mellannamn". Note that there are specific rules that indicate what names may be taken as a mellannamn in different Scandinavian countries
* <!-- end-model-doc -->
* @see #MID
* @model
* @generated
* @ordered
*/
public static final int MID_VALUE = 8;
/**
* The '<em><b>CL</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Callme : Callme is used to indicate which of the various name parts is used when interacting with the person
* <!-- end-model-doc -->
* @see #CL
* @model
* @generated
* @ordered
*/
public static final int CL_VALUE = 9;
/**
* The '<em><b>IN</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Initial : Indicates that a name part is just an initial. Initials do not imply a trailing period since this would not work with non-Latin scripts. Initials may consist of more than one letter, e.g., "Ph." could stand for "Philippe" or "Th." for "Thomas"
* <!-- end-model-doc -->
* @see #IN
* @model
* @generated
* @ordered
*/
public static final int IN_VALUE = 10;
/**
* The '<em><b>PFX</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Prefix : A prefix has a strong association to the immediately following name part. A prefix has no implicit trailing white space (it has implicit leading white space though).
* <!-- end-model-doc -->
* @see #PFX
* @model
* @generated
* @ordered
*/
public static final int PFX_VALUE = 11;
/**
* The '<em><b>SFX</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Suffix : A suffix has a strong association to the immediately preceding name part. A suffix has no implicit leading white space (it has implicit trailing white space though).
* <!-- end-model-doc -->
* @see #SFX
* @model
* @generated
* @ordered
*/
public static final int SFX_VALUE = 12;
/**
* An array of all the '<em><b>Entity Name Part Qualifier</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final EntityNamePartQualifier[] VALUES_ARRAY =
new EntityNamePartQualifier[] {
LS,
AC,
NB,
PR,
HON,
BR,
AD,
SP,
MID,
CL,
IN,
PFX,
SFX,
};
/**
* A public read-only list of all the '<em><b>Entity Name Part Qualifier</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<EntityNamePartQualifier> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
EntityNamePartQualifier result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
EntityNamePartQualifier result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Entity Name Part Qualifier</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static EntityNamePartQualifier get(int value) {
switch (value) {
case LS_VALUE: return LS;
case AC_VALUE: return AC;
case NB_VALUE: return NB;
case PR_VALUE: return PR;
case HON_VALUE: return HON;
case BR_VALUE: return BR;
case AD_VALUE: return AD;
case SP_VALUE: return SP;
case MID_VALUE: return MID;
case CL_VALUE: return CL;
case IN_VALUE: return IN;
case PFX_VALUE: return PFX;
case SFX_VALUE: return SFX;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EntityNamePartQualifier(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //EntityNamePartQualifier
|
172172_14 | /**
*/
package org.hl7.fhir;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Link Type List</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.hl7.fhir.FhirPackage#getLinkTypeList()
* @model extendedMetaData="name='LinkType-list'"
* @generated
*/
public enum LinkTypeList implements Enumerator {
/**
* The '<em><b>Replace</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REPLACE_VALUE
* @generated
* @ordered
*/
REPLACE(0, "replace", "replace"),
/**
* The '<em><b>Refer</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REFER_VALUE
* @generated
* @ordered
*/
REFER(1, "refer", "refer"),
/**
* The '<em><b>Seealso</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SEEALSO_VALUE
* @generated
* @ordered
*/
SEEALSO(2, "seealso", "seealso");
/**
* The '<em><b>Replace</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains the link.
* vervangen
* <!-- end-model-doc -->
* @see #REPLACE
* @model name="replace"
* @generated
* @ordered
*/
public static final int REPLACE_VALUE = 0;
/**
* The '<em><b>Refer</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information
* verwijzing
* <!-- end-model-doc -->
* @see #REFER
* @model name="refer"
* @generated
* @ordered
*/
public static final int REFER_VALUE = 1;
/**
* The '<em><b>Seealso</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.
* zie ook
* <!-- end-model-doc -->
* @see #SEEALSO
* @model name="seealso"
* @generated
* @ordered
*/
public static final int SEEALSO_VALUE = 2;
/**
* An array of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final LinkTypeList[] VALUES_ARRAY =
new LinkTypeList[] {
REPLACE,
REFER,
SEEALSO,
};
/**
* A public read-only list of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<LinkTypeList> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(int value) {
switch (value) {
case REPLACE_VALUE: return REPLACE;
case REFER_VALUE: return REFER;
case SEEALSO_VALUE: return SEEALSO;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private LinkTypeList(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //LinkTypeList
| swmuir/mdht-fhir | plugins/org.eclipse.mdht.fhir.xsd/src/org/hl7/fhir/LinkTypeList.java | 1,999 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
*/
package org.hl7.fhir;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Link Type List</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.hl7.fhir.FhirPackage#getLinkTypeList()
* @model extendedMetaData="name='LinkType-list'"
* @generated
*/
public enum LinkTypeList implements Enumerator {
/**
* The '<em><b>Replace</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REPLACE_VALUE
* @generated
* @ordered
*/
REPLACE(0, "replace", "replace"),
/**
* The '<em><b>Refer</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REFER_VALUE
* @generated
* @ordered
*/
REFER(1, "refer", "refer"),
/**
* The '<em><b>Seealso</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SEEALSO_VALUE
* @generated
* @ordered
*/
SEEALSO(2, "seealso", "seealso");
/**
* The '<em><b>Replace</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains the link.
* vervangen
* <!-- end-model-doc -->
* @see #REPLACE
* @model name="replace"
* @generated
* @ordered
*/
public static final int REPLACE_VALUE = 0;
/**
* The '<em><b>Refer</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information
* verwijzing
* <!-- end-model-doc -->
* @see #REFER
* @model name="refer"
* @generated
* @ordered
*/
public static final int REFER_VALUE = 1;
/**
* The '<em><b>Seealso</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.
* zie ook
* <!-- end-model-doc -->
* @see #SEEALSO
* @model name="seealso"
* @generated
* @ordered
*/
public static final int SEEALSO_VALUE = 2;
/**
* An array of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final LinkTypeList[] VALUES_ARRAY =
new LinkTypeList[] {
REPLACE,
REFER,
SEEALSO,
};
/**
* A public read-only list of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<LinkTypeList> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(int value) {
switch (value) {
case REPLACE_VALUE: return REPLACE;
case REFER_VALUE: return REFER;
case SEEALSO_VALUE: return SEEALSO;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc --><SUF>*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private LinkTypeList(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //LinkTypeList
|
141318_26 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.ncpdp.uml.telecom.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.ncpdp.uml.ecl.OtherPharmacyIndicator;
import org.ncpdp.uml.ecl.OtherPrescriberIndicator;
import org.ncpdp.uml.ecl.ReasonforServiceCode;
import org.ncpdp.uml.telecom.Field;
import org.ncpdp.uml.telecom.ResponseDURPPSSegment;
import org.ncpdp.uml.telecom.TelecomPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Response DURPPS Segment</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getSegmentIdentification <em>Segment Identification</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurppsResponseCodeCounter <em>Durpps Response Code Counter</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getReasonForServiceCode <em>Reason For Service Code</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getClinicalSignificanceCode <em>Clinical Significance Code</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getOtherPharmacyIndicator <em>Other Pharmacy Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getPreviousDateOfFill <em>Previous Date Of Fill</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getQuantityOfPreviousFill <em>Quantity Of Previous Fill</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDatabaseIndicator <em>Database Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getOtherPrescriberIndicator <em>Other Prescriber Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurFreeTextMessage <em>Dur Free Text Message</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurAdditionalText <em>Dur Additional Text</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ResponseDURPPSSegmentImpl extends EObjectImpl implements ResponseDURPPSSegment {
/**
* The cached value of the '{@link #getSegmentIdentification() <em>Segment Identification</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSegmentIdentification()
* @generated
* @ordered
*/
protected EList<String> segmentIdentification;
/**
* The cached value of the '{@link #getDurppsResponseCodeCounter() <em>Durpps Response Code Counter</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurppsResponseCodeCounter()
* @generated
* @ordered
*/
protected EList<Field> durppsResponseCodeCounter;
/**
* The cached value of the '{@link #getReasonForServiceCode() <em>Reason For Service Code</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReasonForServiceCode()
* @generated
* @ordered
*/
protected EList<ReasonforServiceCode> reasonForServiceCode;
/**
* The cached value of the '{@link #getClinicalSignificanceCode() <em>Clinical Significance Code</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClinicalSignificanceCode()
* @generated
* @ordered
*/
protected EList<Field> clinicalSignificanceCode;
/**
* The cached value of the '{@link #getOtherPharmacyIndicator() <em>Other Pharmacy Indicator</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherPharmacyIndicator()
* @generated
* @ordered
*/
protected EList<OtherPharmacyIndicator> otherPharmacyIndicator;
/**
* The cached value of the '{@link #getPreviousDateOfFill() <em>Previous Date Of Fill</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPreviousDateOfFill()
* @generated
* @ordered
*/
protected EList<Field> previousDateOfFill;
/**
* The cached value of the '{@link #getQuantityOfPreviousFill() <em>Quantity Of Previous Fill</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getQuantityOfPreviousFill()
* @generated
* @ordered
*/
protected EList<Field> quantityOfPreviousFill;
/**
* The cached value of the '{@link #getDatabaseIndicator() <em>Database Indicator</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDatabaseIndicator()
* @generated
* @ordered
*/
protected EList<Field> databaseIndicator;
/**
* The cached value of the '{@link #getOtherPrescriberIndicator() <em>Other Prescriber Indicator</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherPrescriberIndicator()
* @generated
* @ordered
*/
protected EList<OtherPrescriberIndicator> otherPrescriberIndicator;
/**
* The cached value of the '{@link #getDurFreeTextMessage() <em>Dur Free Text Message</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurFreeTextMessage()
* @generated
* @ordered
*/
protected EList<Field> durFreeTextMessage;
/**
* The cached value of the '{@link #getDurAdditionalText() <em>Dur Additional Text</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurAdditionalText()
* @generated
* @ordered
*/
protected EList<Field> durAdditionalText;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ResponseDURPPSSegmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return TelecomPackage.Literals.RESPONSE_DURPPS_SEGMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<String> getSegmentIdentification() {
if (segmentIdentification == null) {
segmentIdentification = new EDataTypeUniqueEList<String>(String.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION);
}
return segmentIdentification;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurppsResponseCodeCounter() {
if (durppsResponseCodeCounter == null) {
durppsResponseCodeCounter = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER);
}
return durppsResponseCodeCounter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ReasonforServiceCode> getReasonForServiceCode() {
if (reasonForServiceCode == null) {
reasonForServiceCode = new EDataTypeUniqueEList<ReasonforServiceCode>(ReasonforServiceCode.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE);
}
return reasonForServiceCode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getClinicalSignificanceCode() {
if (clinicalSignificanceCode == null) {
clinicalSignificanceCode = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE);
}
return clinicalSignificanceCode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OtherPharmacyIndicator> getOtherPharmacyIndicator() {
if (otherPharmacyIndicator == null) {
otherPharmacyIndicator = new EDataTypeUniqueEList<OtherPharmacyIndicator>(OtherPharmacyIndicator.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR);
}
return otherPharmacyIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getPreviousDateOfFill() {
if (previousDateOfFill == null) {
previousDateOfFill = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL);
}
return previousDateOfFill;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getQuantityOfPreviousFill() {
if (quantityOfPreviousFill == null) {
quantityOfPreviousFill = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL);
}
return quantityOfPreviousFill;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDatabaseIndicator() {
if (databaseIndicator == null) {
databaseIndicator = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR);
}
return databaseIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OtherPrescriberIndicator> getOtherPrescriberIndicator() {
if (otherPrescriberIndicator == null) {
otherPrescriberIndicator = new EDataTypeUniqueEList<OtherPrescriberIndicator>(OtherPrescriberIndicator.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR);
}
return otherPrescriberIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurFreeTextMessage() {
if (durFreeTextMessage == null) {
durFreeTextMessage = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE);
}
return durFreeTextMessage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurAdditionalText() {
if (durAdditionalText == null) {
durAdditionalText = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT);
}
return durAdditionalText;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return ((InternalEList<?>)getDurppsResponseCodeCounter()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return ((InternalEList<?>)getClinicalSignificanceCode()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return ((InternalEList<?>)getPreviousDateOfFill()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return ((InternalEList<?>)getQuantityOfPreviousFill()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return ((InternalEList<?>)getDatabaseIndicator()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return ((InternalEList<?>)getDurFreeTextMessage()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return ((InternalEList<?>)getDurAdditionalText()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
return getSegmentIdentification();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return getDurppsResponseCodeCounter();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
return getReasonForServiceCode();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return getClinicalSignificanceCode();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
return getOtherPharmacyIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return getPreviousDateOfFill();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return getQuantityOfPreviousFill();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return getDatabaseIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
return getOtherPrescriberIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return getDurFreeTextMessage();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return getDurAdditionalText();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
getSegmentIdentification().clear();
getSegmentIdentification().addAll((Collection<? extends String>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
getDurppsResponseCodeCounter().clear();
getDurppsResponseCodeCounter().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
getReasonForServiceCode().clear();
getReasonForServiceCode().addAll((Collection<? extends ReasonforServiceCode>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
getClinicalSignificanceCode().clear();
getClinicalSignificanceCode().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
getOtherPharmacyIndicator().clear();
getOtherPharmacyIndicator().addAll((Collection<? extends OtherPharmacyIndicator>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
getPreviousDateOfFill().clear();
getPreviousDateOfFill().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
getQuantityOfPreviousFill().clear();
getQuantityOfPreviousFill().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
getDatabaseIndicator().clear();
getDatabaseIndicator().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
getOtherPrescriberIndicator().clear();
getOtherPrescriberIndicator().addAll((Collection<? extends OtherPrescriberIndicator>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
getDurFreeTextMessage().clear();
getDurFreeTextMessage().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
getDurAdditionalText().clear();
getDurAdditionalText().addAll((Collection<? extends Field>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
getSegmentIdentification().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
getDurppsResponseCodeCounter().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
getReasonForServiceCode().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
getClinicalSignificanceCode().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
getOtherPharmacyIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
getPreviousDateOfFill().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
getQuantityOfPreviousFill().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
getDatabaseIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
getOtherPrescriberIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
getDurFreeTextMessage().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
getDurAdditionalText().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
return segmentIdentification != null && !segmentIdentification.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return durppsResponseCodeCounter != null && !durppsResponseCodeCounter.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
return reasonForServiceCode != null && !reasonForServiceCode.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return clinicalSignificanceCode != null && !clinicalSignificanceCode.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
return otherPharmacyIndicator != null && !otherPharmacyIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return previousDateOfFill != null && !previousDateOfFill.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return quantityOfPreviousFill != null && !quantityOfPreviousFill.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return databaseIndicator != null && !databaseIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
return otherPrescriberIndicator != null && !otherPrescriberIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return durFreeTextMessage != null && !durFreeTextMessage.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return durAdditionalText != null && !durAdditionalText.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (segmentIdentification: ");
result.append(segmentIdentification);
result.append(", reasonForServiceCode: ");
result.append(reasonForServiceCode);
result.append(", otherPharmacyIndicator: ");
result.append(otherPharmacyIndicator);
result.append(", otherPrescriberIndicator: ");
result.append(otherPrescriberIndicator);
result.append(')');
return result.toString();
}
} //ResponseDURPPSSegmentImpl
| swmuir/xxxxx | ncpdp/models/org.ncpdp.uml.telecom/src/org/ncpdp/uml/telecom/impl/ResponseDURPPSSegmentImpl.java | 7,370 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.ncpdp.uml.telecom.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.ncpdp.uml.ecl.OtherPharmacyIndicator;
import org.ncpdp.uml.ecl.OtherPrescriberIndicator;
import org.ncpdp.uml.ecl.ReasonforServiceCode;
import org.ncpdp.uml.telecom.Field;
import org.ncpdp.uml.telecom.ResponseDURPPSSegment;
import org.ncpdp.uml.telecom.TelecomPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Response DURPPS Segment</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getSegmentIdentification <em>Segment Identification</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurppsResponseCodeCounter <em>Durpps Response Code Counter</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getReasonForServiceCode <em>Reason For Service Code</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getClinicalSignificanceCode <em>Clinical Significance Code</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getOtherPharmacyIndicator <em>Other Pharmacy Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getPreviousDateOfFill <em>Previous Date Of Fill</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getQuantityOfPreviousFill <em>Quantity Of Previous Fill</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDatabaseIndicator <em>Database Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getOtherPrescriberIndicator <em>Other Prescriber Indicator</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurFreeTextMessage <em>Dur Free Text Message</em>}</li>
* <li>{@link org.ncpdp.uml.telecom.impl.ResponseDURPPSSegmentImpl#getDurAdditionalText <em>Dur Additional Text</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ResponseDURPPSSegmentImpl extends EObjectImpl implements ResponseDURPPSSegment {
/**
* The cached value of the '{@link #getSegmentIdentification() <em>Segment Identification</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSegmentIdentification()
* @generated
* @ordered
*/
protected EList<String> segmentIdentification;
/**
* The cached value of the '{@link #getDurppsResponseCodeCounter() <em>Durpps Response Code Counter</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurppsResponseCodeCounter()
* @generated
* @ordered
*/
protected EList<Field> durppsResponseCodeCounter;
/**
* The cached value of the '{@link #getReasonForServiceCode() <em>Reason For Service Code</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReasonForServiceCode()
* @generated
* @ordered
*/
protected EList<ReasonforServiceCode> reasonForServiceCode;
/**
* The cached value of the '{@link #getClinicalSignificanceCode() <em>Clinical Significance Code</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClinicalSignificanceCode()
* @generated
* @ordered
*/
protected EList<Field> clinicalSignificanceCode;
/**
* The cached value of the '{@link #getOtherPharmacyIndicator() <em>Other Pharmacy Indicator</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherPharmacyIndicator()
* @generated
* @ordered
*/
protected EList<OtherPharmacyIndicator> otherPharmacyIndicator;
/**
* The cached value of the '{@link #getPreviousDateOfFill() <em>Previous Date Of Fill</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPreviousDateOfFill()
* @generated
* @ordered
*/
protected EList<Field> previousDateOfFill;
/**
* The cached value of the '{@link #getQuantityOfPreviousFill() <em>Quantity Of Previous Fill</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getQuantityOfPreviousFill()
* @generated
* @ordered
*/
protected EList<Field> quantityOfPreviousFill;
/**
* The cached value of the '{@link #getDatabaseIndicator() <em>Database Indicator</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDatabaseIndicator()
* @generated
* @ordered
*/
protected EList<Field> databaseIndicator;
/**
* The cached value of the '{@link #getOtherPrescriberIndicator() <em>Other Prescriber Indicator</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherPrescriberIndicator()
* @generated
* @ordered
*/
protected EList<OtherPrescriberIndicator> otherPrescriberIndicator;
/**
* The cached value of the '{@link #getDurFreeTextMessage() <em>Dur Free Text Message</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurFreeTextMessage()
* @generated
* @ordered
*/
protected EList<Field> durFreeTextMessage;
/**
* The cached value of the '{@link #getDurAdditionalText() <em>Dur Additional Text</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDurAdditionalText()
* @generated
* @ordered
*/
protected EList<Field> durAdditionalText;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ResponseDURPPSSegmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return TelecomPackage.Literals.RESPONSE_DURPPS_SEGMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<String> getSegmentIdentification() {
if (segmentIdentification == null) {
segmentIdentification = new EDataTypeUniqueEList<String>(String.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION);
}
return segmentIdentification;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurppsResponseCodeCounter() {
if (durppsResponseCodeCounter == null) {
durppsResponseCodeCounter = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER);
}
return durppsResponseCodeCounter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ReasonforServiceCode> getReasonForServiceCode() {
if (reasonForServiceCode == null) {
reasonForServiceCode = new EDataTypeUniqueEList<ReasonforServiceCode>(ReasonforServiceCode.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE);
}
return reasonForServiceCode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getClinicalSignificanceCode() {
if (clinicalSignificanceCode == null) {
clinicalSignificanceCode = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE);
}
return clinicalSignificanceCode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OtherPharmacyIndicator> getOtherPharmacyIndicator() {
if (otherPharmacyIndicator == null) {
otherPharmacyIndicator = new EDataTypeUniqueEList<OtherPharmacyIndicator>(OtherPharmacyIndicator.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR);
}
return otherPharmacyIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getPreviousDateOfFill() {
if (previousDateOfFill == null) {
previousDateOfFill = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL);
}
return previousDateOfFill;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getQuantityOfPreviousFill() {
if (quantityOfPreviousFill == null) {
quantityOfPreviousFill = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL);
}
return quantityOfPreviousFill;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDatabaseIndicator() {
if (databaseIndicator == null) {
databaseIndicator = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR);
}
return databaseIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OtherPrescriberIndicator> getOtherPrescriberIndicator() {
if (otherPrescriberIndicator == null) {
otherPrescriberIndicator = new EDataTypeUniqueEList<OtherPrescriberIndicator>(OtherPrescriberIndicator.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR);
}
return otherPrescriberIndicator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurFreeTextMessage() {
if (durFreeTextMessage == null) {
durFreeTextMessage = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE);
}
return durFreeTextMessage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getDurAdditionalText() {
if (durAdditionalText == null) {
durAdditionalText = new EObjectContainmentEList<Field>(Field.class, this, TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT);
}
return durAdditionalText;
}
/**
* <!-- begin-user-doc -->
<SUF>*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return ((InternalEList<?>)getDurppsResponseCodeCounter()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return ((InternalEList<?>)getClinicalSignificanceCode()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return ((InternalEList<?>)getPreviousDateOfFill()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return ((InternalEList<?>)getQuantityOfPreviousFill()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return ((InternalEList<?>)getDatabaseIndicator()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return ((InternalEList<?>)getDurFreeTextMessage()).basicRemove(otherEnd, msgs);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return ((InternalEList<?>)getDurAdditionalText()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
return getSegmentIdentification();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return getDurppsResponseCodeCounter();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
return getReasonForServiceCode();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return getClinicalSignificanceCode();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
return getOtherPharmacyIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return getPreviousDateOfFill();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return getQuantityOfPreviousFill();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return getDatabaseIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
return getOtherPrescriberIndicator();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return getDurFreeTextMessage();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return getDurAdditionalText();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
getSegmentIdentification().clear();
getSegmentIdentification().addAll((Collection<? extends String>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
getDurppsResponseCodeCounter().clear();
getDurppsResponseCodeCounter().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
getReasonForServiceCode().clear();
getReasonForServiceCode().addAll((Collection<? extends ReasonforServiceCode>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
getClinicalSignificanceCode().clear();
getClinicalSignificanceCode().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
getOtherPharmacyIndicator().clear();
getOtherPharmacyIndicator().addAll((Collection<? extends OtherPharmacyIndicator>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
getPreviousDateOfFill().clear();
getPreviousDateOfFill().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
getQuantityOfPreviousFill().clear();
getQuantityOfPreviousFill().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
getDatabaseIndicator().clear();
getDatabaseIndicator().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
getOtherPrescriberIndicator().clear();
getOtherPrescriberIndicator().addAll((Collection<? extends OtherPrescriberIndicator>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
getDurFreeTextMessage().clear();
getDurFreeTextMessage().addAll((Collection<? extends Field>)newValue);
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
getDurAdditionalText().clear();
getDurAdditionalText().addAll((Collection<? extends Field>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
getSegmentIdentification().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
getDurppsResponseCodeCounter().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
getReasonForServiceCode().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
getClinicalSignificanceCode().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
getOtherPharmacyIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
getPreviousDateOfFill().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
getQuantityOfPreviousFill().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
getDatabaseIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
getOtherPrescriberIndicator().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
getDurFreeTextMessage().clear();
return;
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
getDurAdditionalText().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__SEGMENT_IDENTIFICATION:
return segmentIdentification != null && !segmentIdentification.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DURPPS_RESPONSE_CODE_COUNTER:
return durppsResponseCodeCounter != null && !durppsResponseCodeCounter.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__REASON_FOR_SERVICE_CODE:
return reasonForServiceCode != null && !reasonForServiceCode.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__CLINICAL_SIGNIFICANCE_CODE:
return clinicalSignificanceCode != null && !clinicalSignificanceCode.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PHARMACY_INDICATOR:
return otherPharmacyIndicator != null && !otherPharmacyIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__PREVIOUS_DATE_OF_FILL:
return previousDateOfFill != null && !previousDateOfFill.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__QUANTITY_OF_PREVIOUS_FILL:
return quantityOfPreviousFill != null && !quantityOfPreviousFill.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DATABASE_INDICATOR:
return databaseIndicator != null && !databaseIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__OTHER_PRESCRIBER_INDICATOR:
return otherPrescriberIndicator != null && !otherPrescriberIndicator.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_FREE_TEXT_MESSAGE:
return durFreeTextMessage != null && !durFreeTextMessage.isEmpty();
case TelecomPackage.RESPONSE_DURPPS_SEGMENT__DUR_ADDITIONAL_TEXT:
return durAdditionalText != null && !durAdditionalText.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (segmentIdentification: ");
result.append(segmentIdentification);
result.append(", reasonForServiceCode: ");
result.append(reasonForServiceCode);
result.append(", otherPharmacyIndicator: ");
result.append(otherPharmacyIndicator);
result.append(", otherPrescriberIndicator: ");
result.append(otherPrescriberIndicator);
result.append(')');
return result.toString();
}
} //ResponseDURPPSSegmentImpl
|
204525_14 | package week1;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class MiniAktk {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
throw new RuntimeException("Exactly one command line argument (path) required");
}
Path path = Paths.get(args[0]);
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Map<Character, Integer> environment = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
line = removeComment(line);
if (line.startsWith("print ")) { // print järel peab olema tühik
String expression = line.substring(6);
System.out.println(evaluateExpression(expression, environment));
}
else if (line.contains("=")) {
String[] parts = line.split("=");
if (parts.length != 2) {
throw new RuntimeException("Malformed assignment");
}
String trimmed = parts[0].trim();
if (trimmed.length() != 1) {
throw new RuntimeException("Variable name must be 1 character");
}
char variableName = trimmed.charAt(0);
if (!Character.isLetter(variableName)) {
throw new RuntimeException("Variable name must be a letter");
}
String expression = parts[1];
environment.put(variableName, evaluateExpression(expression, environment));
}
else if (!line.trim().isEmpty()) { // tühi rida pole viga
throw new RuntimeException("Malformed line: " + line);
}
}
}
}
/**
* Eemaldab realt kommentaari, kui see seal on.
*/
private static String removeComment(String line) {
if (line.contains("#")) return line.substring(0, line.indexOf('#'));
else return line;
}
private static int evaluateExpression(String expression, Map<Character, Integer> environment) {
// Ümbritseme liitmised tühikutega, asendame lahutamise negatiivse arvu liitmisega,
// näiteks teisendame "a +b-c" kujule "a + b + -c", siis saab arvud lihtsalt kokku liita!
// (Eeldame, et esialgses avaldises on ainult märgita täisarvud)
expression = expression.replace("+", " + ").replace("-", " + -");
String[] summands = expression.split("\\+");
int sum = 0;
for (String summand : summands) {
sum += evaluateSummand(summand.trim(), environment);
}
return sum;
}
/*
* Väärtustab märgita või miinusega täisarvu või muutujanime.
*/
private static int evaluateSummand(String summand, Map<Character, Integer> environment) {
int sign = 1;
summand = summand.trim();
if (summand.startsWith("-")) {
sign = -1;
summand = summand.substring(1).trim();
}
// proovime täisarvuna tõlgendada, kui ei saa, siis peaks olema muutuja
try {
return sign * Integer.parseInt(summand);
} catch (NumberFormatException e) {
char variableName = summand.charAt(0);
if (environment.containsKey(variableName)) {
return sign * environment.get(variableName);
}
else {
throw new RuntimeException("Variable " + variableName + " undefined");
}
}
}
/**
* Alternatiivne lahendus: sümbolhaaval avaldise väärtustamine.
* Võrdle Exercise3 eval näidislahendusega:
* * Miinustega arvestamiseks piisab sign muutuja lisamisest.
* * Vigade tuvastamiseks läheb vaja ebatriviaalseid abimuutujate kombinatsioone.
*/
private static int evaluateExpressionAlt(String expression, Map<Character, Integer> environment) {
// avaldise väärtustamiseks vajalikud muutujad
int sum = 0;
int sign = 1; // "märk" (1 või -1) millega järgmine number/muutuja liidetakse
int current = 0;
// vigaste avaldiste tuvastamiseks vajalikud muutujad
boolean needOperand = true; // kas järgmine sümbol PEAB olema number või muutuja nimi?
boolean acceptDigit = true; // kas järgmine sümbol VÕIB olla number?
for (char c : expression.toCharArray()) {
if (Character.isDigit(c) && acceptDigit) {
current = 10 * current + Character.getNumericValue(c);
needOperand = false;
// endiselt acceptDigit on true
} else if (Character.isLetter(c) && needOperand) {
current = environment.get(c);
acceptDigit = needOperand = false;
} else if ((c == '+' || c == '-') && !needOperand) {
sum += sign * current;
sign = c == '+' ? 1 : -1;
current = 0;
acceptDigit = needOperand = true;
} else if (c == ' ') {
if (!needOperand) {
acceptDigit = false;
}
} else {
// raske öelda, mis nüüd täpselt viga oli
throw new RuntimeException("Malformed expression");
}
}
if (needOperand) {
throw new RuntimeException("Expected operand at the end of expression");
}
return sum + sign * current;
}
}
| sws-lab/akt2024 | sols/week1/MiniAktk.java | 1,674 | // endiselt acceptDigit on true | line_comment | nl | package week1;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class MiniAktk {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
throw new RuntimeException("Exactly one command line argument (path) required");
}
Path path = Paths.get(args[0]);
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Map<Character, Integer> environment = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
line = removeComment(line);
if (line.startsWith("print ")) { // print järel peab olema tühik
String expression = line.substring(6);
System.out.println(evaluateExpression(expression, environment));
}
else if (line.contains("=")) {
String[] parts = line.split("=");
if (parts.length != 2) {
throw new RuntimeException("Malformed assignment");
}
String trimmed = parts[0].trim();
if (trimmed.length() != 1) {
throw new RuntimeException("Variable name must be 1 character");
}
char variableName = trimmed.charAt(0);
if (!Character.isLetter(variableName)) {
throw new RuntimeException("Variable name must be a letter");
}
String expression = parts[1];
environment.put(variableName, evaluateExpression(expression, environment));
}
else if (!line.trim().isEmpty()) { // tühi rida pole viga
throw new RuntimeException("Malformed line: " + line);
}
}
}
}
/**
* Eemaldab realt kommentaari, kui see seal on.
*/
private static String removeComment(String line) {
if (line.contains("#")) return line.substring(0, line.indexOf('#'));
else return line;
}
private static int evaluateExpression(String expression, Map<Character, Integer> environment) {
// Ümbritseme liitmised tühikutega, asendame lahutamise negatiivse arvu liitmisega,
// näiteks teisendame "a +b-c" kujule "a + b + -c", siis saab arvud lihtsalt kokku liita!
// (Eeldame, et esialgses avaldises on ainult märgita täisarvud)
expression = expression.replace("+", " + ").replace("-", " + -");
String[] summands = expression.split("\\+");
int sum = 0;
for (String summand : summands) {
sum += evaluateSummand(summand.trim(), environment);
}
return sum;
}
/*
* Väärtustab märgita või miinusega täisarvu või muutujanime.
*/
private static int evaluateSummand(String summand, Map<Character, Integer> environment) {
int sign = 1;
summand = summand.trim();
if (summand.startsWith("-")) {
sign = -1;
summand = summand.substring(1).trim();
}
// proovime täisarvuna tõlgendada, kui ei saa, siis peaks olema muutuja
try {
return sign * Integer.parseInt(summand);
} catch (NumberFormatException e) {
char variableName = summand.charAt(0);
if (environment.containsKey(variableName)) {
return sign * environment.get(variableName);
}
else {
throw new RuntimeException("Variable " + variableName + " undefined");
}
}
}
/**
* Alternatiivne lahendus: sümbolhaaval avaldise väärtustamine.
* Võrdle Exercise3 eval näidislahendusega:
* * Miinustega arvestamiseks piisab sign muutuja lisamisest.
* * Vigade tuvastamiseks läheb vaja ebatriviaalseid abimuutujate kombinatsioone.
*/
private static int evaluateExpressionAlt(String expression, Map<Character, Integer> environment) {
// avaldise väärtustamiseks vajalikud muutujad
int sum = 0;
int sign = 1; // "märk" (1 või -1) millega järgmine number/muutuja liidetakse
int current = 0;
// vigaste avaldiste tuvastamiseks vajalikud muutujad
boolean needOperand = true; // kas järgmine sümbol PEAB olema number või muutuja nimi?
boolean acceptDigit = true; // kas järgmine sümbol VÕIB olla number?
for (char c : expression.toCharArray()) {
if (Character.isDigit(c) && acceptDigit) {
current = 10 * current + Character.getNumericValue(c);
needOperand = false;
// endiselt acceptDigit<SUF>
} else if (Character.isLetter(c) && needOperand) {
current = environment.get(c);
acceptDigit = needOperand = false;
} else if ((c == '+' || c == '-') && !needOperand) {
sum += sign * current;
sign = c == '+' ? 1 : -1;
current = 0;
acceptDigit = needOperand = true;
} else if (c == ' ') {
if (!needOperand) {
acceptDigit = false;
}
} else {
// raske öelda, mis nüüd täpselt viga oli
throw new RuntimeException("Malformed expression");
}
}
if (needOperand) {
throw new RuntimeException("Expected operand at the end of expression");
}
return sum + sign * current;
}
}
|
7739_29 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.menu;
import org.mozilla.gecko.R;
import org.mozilla.gecko.widget.Divider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends ListView
implements Menu,
MenuItem.OnMenuItemClickListener,
AdapterView.OnItemClickListener,
GeckoMenuItem.OnVisibilityChangedListener,
GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
/*
* A callback for a menu item selected event.
*/
public static interface Callback {
// Called when a menu item is selected, with the actual menu item as the argument.
public boolean onMenuItemSelected(MenuItem item);
}
/*
* An interface for a presenter to show the menu.
* Either an Activity or a View can be a presenter, that can watch for events
* and show/hide menu.
*/
public static interface MenuPresenter {
// Open the menu.
public void openMenu();
// Show the actual view contaning the menu items. This can either be a parent or sub-menu.
public void showMenu(View menu);
// Close the menu.
public void closeMenu();
}
/*
* An interface for a presenter of action-items.
* Either an Activity or a View can be a presenter, that can watch for events
* and add/remove action-items. If not ActionItemBarPresenter, the menu uses a
* DefaultActionItemBarPresenter, that shows the action-items as a header over list-view.
*/
public static interface ActionItemBarPresenter {
// Add an action-item.
public void addActionItem(View actionItem);
// Remove an action-item based on the index. The index used while adding.
public void removeActionItem(int index);
// Get the number of action-items shown by the presenter.
public int getActionItemsCount();
}
protected static final int NO_ID = 0;
// List of all menu items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to a callback for menu events.
private Callback mCallback;
// Reference to menu presenter.
private MenuPresenter mMenuPresenter;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
// Adapter to hold the list of menu items.
private MenuItemsAdapter mAdapter;
// ActionBar to show the menu items as icons.
private LinearLayout mActionBar;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Add a header view that acts as an action-bar.
mActionBar = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.menu_action_bar, null);
// Attach an adapter.
mAdapter = new MenuItemsAdapter(context);
setAdapter(mAdapter);
setOnItemClickListener(this);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
mActionItemBarPresenter = new DefaultActionItemBarPresenter(mContext, mActionBar);
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(this);
menuItem.setOnMenuItemClickListener(this);
mAdapter.addMenuItem(menuItem);
mItems.add(menuItem);
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(null);
menuItem.setOnMenuItemClickListener(this);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before adding the header view to a list.
setAdapter(null);
addHeaderView(mActionBar);
setAdapter(mAdapter);
}
mActionItems.add(menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
mItems.add(menuItem);
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
MenuItem menuItem = add(groupId, itemId, order, title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
MenuItem menuItem = add(groupId, itemId, order, titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
MenuItem menuItem = add(title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int titleRes) {
MenuItem menuItem = add(titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public void clear() {
}
@Override
public void close() {
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
return menuItem;
} else if (menuItem.hasSubMenu()) {
SubMenu subMenu = menuItem.getSubMenu();
MenuItem item = subMenu.findItem(id);
if (item != null)
return item;
}
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
GeckoMenuItem item = (GeckoMenuItem) findItem(id);
if (item != null) {
if (mActionItems.contains(item)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(item));
mActionItems.remove(item);
mItems.remove(item);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before removing the header view from a list.
setAdapter(null);
removeHeaderView(mActionBar);
setAdapter(mAdapter);
}
return;
}
mAdapter.removeMenuItem(item);
mItems.remove(item);
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
@Override
public void onVisibilityChanged(GeckoMenuItem item, boolean isVisible) {
if (isVisible)
mAdapter.addMenuItem(item);
else
mAdapter.removeMenuItem(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position -= getHeaderViewsCount();
GeckoMenuItem item = mAdapter.getItem(position);
if (item.isEnabled())
item.onClick(item.getLayout());
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!item.hasSubMenu()) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return mCallback.onMenuItemSelected(item);
} else {
// Show the submenu.
if (mMenuPresenter != null)
mMenuPresenter.showMenu((GeckoSubMenu) item.getSubMenu());
return true;
}
}
public boolean onCustomMenuItemClick(MenuItem item, MenuItem.OnMenuItemClickListener listener) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return listener.onMenuItemClick(item);
}
public Callback getCallback() {
return mCallback;
}
public MenuPresenter getMenuPresenter() {
return mMenuPresenter;
}
public void setCallback(Callback callback) {
mCallback = callback;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setCallback(mCallback);
}
}
}
public void setMenuPresenter(MenuPresenter presenter) {
mMenuPresenter = presenter;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setMenuPresenter(mMenuPresenter);
}
}
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
// Action Items are added to the header view by default.
// URL bar can register itself as a presenter, in case it has a different place to show them.
private class DefaultActionItemBarPresenter implements ActionItemBarPresenter {
private Context mContext;
private LinearLayout mContainer;
private List<View> mItems;
public DefaultActionItemBarPresenter(Context context, LinearLayout container) {
mContext = context;
mContainer = container;
mItems = new ArrayList<View>();
}
@Override
public void addActionItem(View actionItem) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(actionItem.getLayoutParams());
params.weight = 1.0f;
actionItem.setLayoutParams(params);
if (mItems.size() > 0) {
Divider divider = new Divider(mContext, null);
divider.setOrientation(Divider.Orientation.VERTICAL);
divider.setBackgroundColor(0xFFD1D5DA);
mContainer.addView(divider);
}
mContainer.addView(actionItem);
mItems.add(actionItem);
}
@Override
public void removeActionItem(int index) {
// Remove the icon and the vertical divider.
mContainer.removeViewAt(index * 2);
if (index != 0)
mContainer.removeViewAt(index * 2 - 1);
mItems.remove(index);
if (mItems.size() == 0)
mContainer.setVisibility(View.GONE);
}
@Override
public int getActionItemsCount() {
return mItems.size();
}
}
// Adapter to bind menu items to the list.
private class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private List<GeckoMenuItem> mItems;
public MenuItemsAdapter(Context context) {
mContext = context;
mItems = new ArrayList<GeckoMenuItem>();
}
@Override
public int getCount() {
return (mItems == null ? 0 : mItems.size());
}
@Override
public GeckoMenuItem getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return mItems.get(position).getLayout();
}
@Override
public int getItemViewType (int position) {
return AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public boolean areAllItemsEnabled() {
for (GeckoMenuItem item : mItems) {
if (!item.isEnabled())
return false;
}
return true;
}
@Override
public boolean isEnabled(int position) {
return getItem(position).isEnabled();
}
public void addMenuItem(GeckoMenuItem menuItem) {
if (mItems.contains(menuItem))
return;
// Insert it in proper order.
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
notifyDataSetChanged();
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
notifyDataSetChanged();
}
public void removeMenuItem(GeckoMenuItem menuItem) {
// Remove it from the list.
mItems.remove(menuItem);
notifyDataSetChanged();
}
public GeckoMenuItem getMenuItem(int id) {
for (GeckoMenuItem item : mItems) {
if (item.getItemId() == id)
return item;
}
return null;
}
}
}
| syg/iontrail | mobile/android/base/menu/GeckoMenu.java | 4,671 | // Insert it in proper order. | line_comment | nl | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.menu;
import org.mozilla.gecko.R;
import org.mozilla.gecko.widget.Divider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends ListView
implements Menu,
MenuItem.OnMenuItemClickListener,
AdapterView.OnItemClickListener,
GeckoMenuItem.OnVisibilityChangedListener,
GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
/*
* A callback for a menu item selected event.
*/
public static interface Callback {
// Called when a menu item is selected, with the actual menu item as the argument.
public boolean onMenuItemSelected(MenuItem item);
}
/*
* An interface for a presenter to show the menu.
* Either an Activity or a View can be a presenter, that can watch for events
* and show/hide menu.
*/
public static interface MenuPresenter {
// Open the menu.
public void openMenu();
// Show the actual view contaning the menu items. This can either be a parent or sub-menu.
public void showMenu(View menu);
// Close the menu.
public void closeMenu();
}
/*
* An interface for a presenter of action-items.
* Either an Activity or a View can be a presenter, that can watch for events
* and add/remove action-items. If not ActionItemBarPresenter, the menu uses a
* DefaultActionItemBarPresenter, that shows the action-items as a header over list-view.
*/
public static interface ActionItemBarPresenter {
// Add an action-item.
public void addActionItem(View actionItem);
// Remove an action-item based on the index. The index used while adding.
public void removeActionItem(int index);
// Get the number of action-items shown by the presenter.
public int getActionItemsCount();
}
protected static final int NO_ID = 0;
// List of all menu items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to a callback for menu events.
private Callback mCallback;
// Reference to menu presenter.
private MenuPresenter mMenuPresenter;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
// Adapter to hold the list of menu items.
private MenuItemsAdapter mAdapter;
// ActionBar to show the menu items as icons.
private LinearLayout mActionBar;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Add a header view that acts as an action-bar.
mActionBar = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.menu_action_bar, null);
// Attach an adapter.
mAdapter = new MenuItemsAdapter(context);
setAdapter(mAdapter);
setOnItemClickListener(this);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
mActionItemBarPresenter = new DefaultActionItemBarPresenter(mContext, mActionBar);
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(this);
menuItem.setOnMenuItemClickListener(this);
mAdapter.addMenuItem(menuItem);
mItems.add(menuItem);
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(null);
menuItem.setOnMenuItemClickListener(this);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before adding the header view to a list.
setAdapter(null);
addHeaderView(mActionBar);
setAdapter(mAdapter);
}
mActionItems.add(menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
mItems.add(menuItem);
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
MenuItem menuItem = add(groupId, itemId, order, title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
MenuItem menuItem = add(groupId, itemId, order, titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
MenuItem menuItem = add(title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int titleRes) {
MenuItem menuItem = add(titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public void clear() {
}
@Override
public void close() {
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
return menuItem;
} else if (menuItem.hasSubMenu()) {
SubMenu subMenu = menuItem.getSubMenu();
MenuItem item = subMenu.findItem(id);
if (item != null)
return item;
}
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
GeckoMenuItem item = (GeckoMenuItem) findItem(id);
if (item != null) {
if (mActionItems.contains(item)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(item));
mActionItems.remove(item);
mItems.remove(item);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before removing the header view from a list.
setAdapter(null);
removeHeaderView(mActionBar);
setAdapter(mAdapter);
}
return;
}
mAdapter.removeMenuItem(item);
mItems.remove(item);
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
@Override
public void onVisibilityChanged(GeckoMenuItem item, boolean isVisible) {
if (isVisible)
mAdapter.addMenuItem(item);
else
mAdapter.removeMenuItem(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position -= getHeaderViewsCount();
GeckoMenuItem item = mAdapter.getItem(position);
if (item.isEnabled())
item.onClick(item.getLayout());
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!item.hasSubMenu()) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return mCallback.onMenuItemSelected(item);
} else {
// Show the submenu.
if (mMenuPresenter != null)
mMenuPresenter.showMenu((GeckoSubMenu) item.getSubMenu());
return true;
}
}
public boolean onCustomMenuItemClick(MenuItem item, MenuItem.OnMenuItemClickListener listener) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return listener.onMenuItemClick(item);
}
public Callback getCallback() {
return mCallback;
}
public MenuPresenter getMenuPresenter() {
return mMenuPresenter;
}
public void setCallback(Callback callback) {
mCallback = callback;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setCallback(mCallback);
}
}
}
public void setMenuPresenter(MenuPresenter presenter) {
mMenuPresenter = presenter;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setMenuPresenter(mMenuPresenter);
}
}
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
// Action Items are added to the header view by default.
// URL bar can register itself as a presenter, in case it has a different place to show them.
private class DefaultActionItemBarPresenter implements ActionItemBarPresenter {
private Context mContext;
private LinearLayout mContainer;
private List<View> mItems;
public DefaultActionItemBarPresenter(Context context, LinearLayout container) {
mContext = context;
mContainer = container;
mItems = new ArrayList<View>();
}
@Override
public void addActionItem(View actionItem) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(actionItem.getLayoutParams());
params.weight = 1.0f;
actionItem.setLayoutParams(params);
if (mItems.size() > 0) {
Divider divider = new Divider(mContext, null);
divider.setOrientation(Divider.Orientation.VERTICAL);
divider.setBackgroundColor(0xFFD1D5DA);
mContainer.addView(divider);
}
mContainer.addView(actionItem);
mItems.add(actionItem);
}
@Override
public void removeActionItem(int index) {
// Remove the icon and the vertical divider.
mContainer.removeViewAt(index * 2);
if (index != 0)
mContainer.removeViewAt(index * 2 - 1);
mItems.remove(index);
if (mItems.size() == 0)
mContainer.setVisibility(View.GONE);
}
@Override
public int getActionItemsCount() {
return mItems.size();
}
}
// Adapter to bind menu items to the list.
private class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private List<GeckoMenuItem> mItems;
public MenuItemsAdapter(Context context) {
mContext = context;
mItems = new ArrayList<GeckoMenuItem>();
}
@Override
public int getCount() {
return (mItems == null ? 0 : mItems.size());
}
@Override
public GeckoMenuItem getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return mItems.get(position).getLayout();
}
@Override
public int getItemViewType (int position) {
return AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public boolean areAllItemsEnabled() {
for (GeckoMenuItem item : mItems) {
if (!item.isEnabled())
return false;
}
return true;
}
@Override
public boolean isEnabled(int position) {
return getItem(position).isEnabled();
}
public void addMenuItem(GeckoMenuItem menuItem) {
if (mItems.contains(menuItem))
return;
// Insert it<SUF>
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
notifyDataSetChanged();
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
notifyDataSetChanged();
}
public void removeMenuItem(GeckoMenuItem menuItem) {
// Remove it from the list.
mItems.remove(menuItem);
notifyDataSetChanged();
}
public GeckoMenuItem getMenuItem(int id) {
for (GeckoMenuItem item : mItems) {
if (item.getItemId() == id)
return item;
}
return null;
}
}
}
|
3591_4 | /*
* Copyright 2010 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.parser;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.sylvanaar.idea.Lua.lang.lexer.LuaElementType;
import com.sylvanaar.idea.Lua.lang.lexer.LuaTokenTypes;
import com.sylvanaar.idea.Lua.lang.luadoc.parser.LuaDocElementTypes;
import com.sylvanaar.idea.Lua.lang.psi.stubs.elements.*;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: Apr 10, 2010
* Time: 3:54:46 PM
*/
public interface LuaElementTypes extends LuaTokenTypes, LuaDocElementTypes {
IElementType EMPTY_INPUT = new LuaElementType("empty input");
IElementType FUNCTION_DEFINITION = new LuaElementType("Function Definition");
IElementType LOCAL_NAME = new LuaElementType("local name");
IElementType LOCAL_NAME_DECL = new LuaElementType("local name declaration");
IElementType GLOBAL_NAME = new LuaElementType("global name");
// IElementType GLOBAL_NAME_DECL = new LuaElementType("global name declaration");
// IElementType GETTABLE = new LuaElementType("get table");
//IElementType GETSELF = new LuaElementType("get self");
LuaStubGlobalDeclarationType GLOBAL_NAME_DECL = new LuaStubGlobalDeclarationType();
LuaStubModuleDeclarationType MODULE_NAME_DECL = new LuaStubModuleDeclarationType();
LuaStubCompoundIdentifierType GETTABLE = new LuaStubCompoundIdentifierType();
//LuaStubElementType<LuaCompoundIdentifierStub, LuaCompoundIdentifier> GETSELF = new
// LuaStubCompoundIdentifierType();
LuaFieldStubType FIELD_NAME = new LuaFieldStubType();
IElementType FILE = LuaParserDefinition.LUA_FILE;
IElementType TABLE_INDEX = new LuaElementType("table index");
IElementType KEY_ASSIGNMENT = new LuaElementType("keyed field initializer");
IElementType IDX_ASSIGNMENT = new LuaElementType("indexed field initializer");
// IElementType REFERENCE = new LuaElementType("Reference");
IElementType COMPOUND_REFERENCE = new LuaElementType("Compound Reference");
IElementType IDENTIFIER_LIST = new LuaElementType("Identifier List");
IElementType STATEMENT = new LuaElementType("Statment");
IElementType LAST_STATEMENT = new LuaElementType("LastStatement");
IElementType EXPR = new LuaElementType("Expression");
IElementType EXPR_LIST = new LuaElementType("Expression List");
IElementType LITERAL_EXPRESSION = new LuaElementType("Literal Expression");
IElementType PARENTHEICAL_EXPRESSION = new LuaElementType("Parentheical Expression");
LuaTableStubType TABLE_CONSTUCTOR = new LuaTableStubType();
IElementType FUNCTION_CALL_ARGS = new LuaElementType("Function Call Args");
IElementType FUNCTION_CALL = new LuaElementType("Function Call Statement");
IElementType FUNCTION_CALL_EXPR = new LuaElementType("Function Call Expression");
IElementType ANONYMOUS_FUNCTION_EXPRESSION = new LuaElementType("Anonymous function expression");
IElementType ASSIGN_STMT = new LuaElementType("Assignment Statement");
IElementType CONDITIONAL_EXPR = new LuaElementType("Conditional Expression");
IElementType LOCAL_DECL_WITH_ASSIGNMENT = new LuaElementType("Local Declaration With Assignment Statement");
IElementType LOCAL_DECL = new LuaElementType("Local Declaration");
IElementType SELF_PARAMETER = new LuaElementType("Implied parameter (self)");
IElementType BLOCK = new LuaElementType("Block");
IElementType UNARY_EXP = new LuaElementType("UnExp");
IElementType BINARY_EXP = new LuaElementType("BinExp");
IElementType UNARY_OP = new LuaElementType("UnOp");
IElementType BINARY_OP = new LuaElementType("BinOp");
IElementType DO_BLOCK = new LuaElementType("Do Block");
IElementType WHILE_BLOCK = new LuaElementType("While Block");
IElementType REPEAT_BLOCK = new LuaElementType("Repeat Block");
IElementType UNTIL_CLAUSE = new LuaElementType("Until Clause");
IElementType GENERIC_FOR_BLOCK = new LuaElementType("Generic For Block");
IElementType IF_THEN_BLOCK = new LuaElementType("If-Then Block");
IElementType NUMERIC_FOR_BLOCK = new LuaElementType("Numeric For Block");
TokenSet EXPRESSION_SET = TokenSet.create(LITERAL_EXPRESSION, BINARY_EXP,
UNARY_EXP, EXPR, ANONYMOUS_FUNCTION_EXPRESSION, FUNCTION_CALL_EXPR, PARENTHEICAL_EXPRESSION);
IElementType RETURN_STATEMENT = new LuaElementType("Return statement");
IElementType RETURN_STATEMENT_WITH_TAIL_CALL = new LuaElementType("Tailcall Return statement");
IElementType LOCAL_FUNCTION = new LuaElementType("local function def");
TokenSet BLOCK_SET = TokenSet.create(FUNCTION_DEFINITION, LOCAL_FUNCTION, ANONYMOUS_FUNCTION_EXPRESSION,
WHILE_BLOCK,
GENERIC_FOR_BLOCK,
IF_THEN_BLOCK,
NUMERIC_FOR_BLOCK,
REPEAT_BLOCK,
DO_BLOCK);
IElementType PARAMETER = new LuaElementType("function parameters");
IElementType PARAMETER_LIST = new LuaElementType("function parameter");
IElementType UPVAL_NAME = new LuaElementType("upvalue name");
IElementType MAIN_CHUNK_VARARGS = new LuaElementType("main chunk args", true);
}
| sylvanaar/IDLua | src/main/java/com/sylvanaar/idea/Lua/lang/parser/LuaElementTypes.java | 1,861 | //IElementType GETSELF = new LuaElementType("get self");
| line_comment | nl | /*
* Copyright 2010 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.parser;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.sylvanaar.idea.Lua.lang.lexer.LuaElementType;
import com.sylvanaar.idea.Lua.lang.lexer.LuaTokenTypes;
import com.sylvanaar.idea.Lua.lang.luadoc.parser.LuaDocElementTypes;
import com.sylvanaar.idea.Lua.lang.psi.stubs.elements.*;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: Apr 10, 2010
* Time: 3:54:46 PM
*/
public interface LuaElementTypes extends LuaTokenTypes, LuaDocElementTypes {
IElementType EMPTY_INPUT = new LuaElementType("empty input");
IElementType FUNCTION_DEFINITION = new LuaElementType("Function Definition");
IElementType LOCAL_NAME = new LuaElementType("local name");
IElementType LOCAL_NAME_DECL = new LuaElementType("local name declaration");
IElementType GLOBAL_NAME = new LuaElementType("global name");
// IElementType GLOBAL_NAME_DECL = new LuaElementType("global name declaration");
// IElementType GETTABLE = new LuaElementType("get table");
//IElementType GETSELF<SUF>
LuaStubGlobalDeclarationType GLOBAL_NAME_DECL = new LuaStubGlobalDeclarationType();
LuaStubModuleDeclarationType MODULE_NAME_DECL = new LuaStubModuleDeclarationType();
LuaStubCompoundIdentifierType GETTABLE = new LuaStubCompoundIdentifierType();
//LuaStubElementType<LuaCompoundIdentifierStub, LuaCompoundIdentifier> GETSELF = new
// LuaStubCompoundIdentifierType();
LuaFieldStubType FIELD_NAME = new LuaFieldStubType();
IElementType FILE = LuaParserDefinition.LUA_FILE;
IElementType TABLE_INDEX = new LuaElementType("table index");
IElementType KEY_ASSIGNMENT = new LuaElementType("keyed field initializer");
IElementType IDX_ASSIGNMENT = new LuaElementType("indexed field initializer");
// IElementType REFERENCE = new LuaElementType("Reference");
IElementType COMPOUND_REFERENCE = new LuaElementType("Compound Reference");
IElementType IDENTIFIER_LIST = new LuaElementType("Identifier List");
IElementType STATEMENT = new LuaElementType("Statment");
IElementType LAST_STATEMENT = new LuaElementType("LastStatement");
IElementType EXPR = new LuaElementType("Expression");
IElementType EXPR_LIST = new LuaElementType("Expression List");
IElementType LITERAL_EXPRESSION = new LuaElementType("Literal Expression");
IElementType PARENTHEICAL_EXPRESSION = new LuaElementType("Parentheical Expression");
LuaTableStubType TABLE_CONSTUCTOR = new LuaTableStubType();
IElementType FUNCTION_CALL_ARGS = new LuaElementType("Function Call Args");
IElementType FUNCTION_CALL = new LuaElementType("Function Call Statement");
IElementType FUNCTION_CALL_EXPR = new LuaElementType("Function Call Expression");
IElementType ANONYMOUS_FUNCTION_EXPRESSION = new LuaElementType("Anonymous function expression");
IElementType ASSIGN_STMT = new LuaElementType("Assignment Statement");
IElementType CONDITIONAL_EXPR = new LuaElementType("Conditional Expression");
IElementType LOCAL_DECL_WITH_ASSIGNMENT = new LuaElementType("Local Declaration With Assignment Statement");
IElementType LOCAL_DECL = new LuaElementType("Local Declaration");
IElementType SELF_PARAMETER = new LuaElementType("Implied parameter (self)");
IElementType BLOCK = new LuaElementType("Block");
IElementType UNARY_EXP = new LuaElementType("UnExp");
IElementType BINARY_EXP = new LuaElementType("BinExp");
IElementType UNARY_OP = new LuaElementType("UnOp");
IElementType BINARY_OP = new LuaElementType("BinOp");
IElementType DO_BLOCK = new LuaElementType("Do Block");
IElementType WHILE_BLOCK = new LuaElementType("While Block");
IElementType REPEAT_BLOCK = new LuaElementType("Repeat Block");
IElementType UNTIL_CLAUSE = new LuaElementType("Until Clause");
IElementType GENERIC_FOR_BLOCK = new LuaElementType("Generic For Block");
IElementType IF_THEN_BLOCK = new LuaElementType("If-Then Block");
IElementType NUMERIC_FOR_BLOCK = new LuaElementType("Numeric For Block");
TokenSet EXPRESSION_SET = TokenSet.create(LITERAL_EXPRESSION, BINARY_EXP,
UNARY_EXP, EXPR, ANONYMOUS_FUNCTION_EXPRESSION, FUNCTION_CALL_EXPR, PARENTHEICAL_EXPRESSION);
IElementType RETURN_STATEMENT = new LuaElementType("Return statement");
IElementType RETURN_STATEMENT_WITH_TAIL_CALL = new LuaElementType("Tailcall Return statement");
IElementType LOCAL_FUNCTION = new LuaElementType("local function def");
TokenSet BLOCK_SET = TokenSet.create(FUNCTION_DEFINITION, LOCAL_FUNCTION, ANONYMOUS_FUNCTION_EXPRESSION,
WHILE_BLOCK,
GENERIC_FOR_BLOCK,
IF_THEN_BLOCK,
NUMERIC_FOR_BLOCK,
REPEAT_BLOCK,
DO_BLOCK);
IElementType PARAMETER = new LuaElementType("function parameters");
IElementType PARAMETER_LIST = new LuaElementType("function parameter");
IElementType UPVAL_NAME = new LuaElementType("upvalue name");
IElementType MAIN_CHUNK_VARARGS = new LuaElementType("main chunk args", true);
}
|
40686_6 | package fr.loria.synalp.jtrans.markup.out;
import fr.loria.synalp.jtrans.graph.StatePool;
import fr.loria.synalp.jtrans.project.*;
import fr.loria.synalp.jtrans.utils.FileUtils;
import java.io.*;
import java.util.Iterator;
import static fr.loria.synalp.jtrans.utils.FileUtils.getUTF8Writer;
import static fr.loria.synalp.jtrans.speechreco.s4.S4mfccBuffer.frame2second;
public class TextGridSaverHelper {
/**
* If true, anonymized words will be replaced with "*ANON*" and their
* phones will not be shown.
*/
public static enum docensort {withNPs, anonymous, both};
public static docensort censorAnonWords = docensort.both;
protected TextGridSaverHelper() {
// Don't let anyone but subclasses instantiate
}
public static void savePraat(Project p,File f,boolean withWords,boolean withPhons) throws IOException {
if (censorAnonWords==docensort.both) {
String ext="";
String s=f.getAbsolutePath();
int i=s.lastIndexOf('.');
if (i>=0) ext=s.substring(i);
File fanon = new File(FileUtils.noExt(s)+"_anon"+ext);
savePraat(true, p, fanon, withWords, withPhons);
savePraat(false, p, f, withWords, withPhons);
} else if (censorAnonWords==docensort.withNPs) {
savePraat(false, p, f, withWords, withPhons);
} else {
savePraat(true,p, f, withWords, withPhons);
}
}
private static void savePraat(
boolean anonymous,
Project p,
File f,
boolean withWords,
boolean withPhons)
throws IOException
{
Writer w = getUTF8Writer(f);
final int frameCount = (int) p.audioSourceTotalFrames;
praatFileHeader(w,
frameCount,
p.speakerCount() * ((withWords?1:0) + (withPhons?1:0)));
int id = 1;
for (int i = 0; i < p.speakerCount(); i++) {
StringBuilder wordSB = new StringBuilder();
StringBuilder phoneSB = new StringBuilder();
int[] wordCount = {0};
int[] phoneCount = {0};
// frame onto which to tack 0-length elements
int lastFrame = 0;
int textidStard2add = -1; String textid2add = "BUG";
Iterator<Phrase> itr = p.phraseIterator(i);
while (itr.hasNext()) {
Phrase phrase = itr.next();
// frame onto which to tack 0-length elements
if (phrase.getInitialAnchor() != null) {
lastFrame = phrase.getInitialAnchor().getFrame();
}
for (Token token: phrase) {
if (token.isAlignable() && token.isAligned()) {
boolean censored = anonymous && token.shouldBeAnonymized();
String tok = token.shouldBeAnonymized()?"*"+token.toString()+"*":token.toString();
int startWfr = token.getFirstNonSilenceFrame();
int endWfr = token.getLastNonSilenceFrame();
lastFrame = token.getSegment().getEndFrame();
if (startWfr<0) {
// ce n'est que un SIL: j'ajoute un mot pour le SIL
// et bien non, en fait, j'ai decide de ne pas faire apparaitre du tout les SIL dans la tier des mots...
// praatInterval(
// wordSB,
// wordCount + 1,
// token.getSegment().getStartFrame(),
// token.getSegment().getEndFrame(),
// censored ? "*ANON*" : tok);
// wordCount++;
} else {
// if (startWfr>token.getSegment().getStartFrame()) {
// // il y a un SIL devant: j'ajoute un mot "SIL" devant
// praatInterval(
// wordSB,
// wordCount + 1,
// token.getSegment().getStartFrame(),
// startWfr,
// StatePool.SILENCE_PHONE);
// wordCount++;
// }
if (textidStard2add>=0) {
// first add a START textid comment with the same frame as the next word
praatInterval(
wordSB,
wordCount,
startWfr,
startWfr-1,
textid2add);
textidStard2add=-1;
}
// cas normal: mot prononcé et aligné
praatInterval(
wordSB,
wordCount,
startWfr,
endWfr,
censored ? "*ANON*" : tok);
lastFrame=endWfr;
// if (endWfr<token.getSegment().getEndFrame()) {
// // il y a un SIL derriere; j'ajoute un mot "SIL" a la fin
// praatInterval(
// wordSB,
// wordCount + 1,
// endWfr,
// token.getSegment().getEndFrame(),
// StatePool.SILENCE_PHONE);
// wordCount++;
// }
}
// dans tous les cas, j'ajoute les phonemes
if (!censored) {
for (Token.Phone phone : token.getPhones()) {
praatInterval(
phoneSB,
phoneCount,
phone.getSegment().getStartFrame(),
phone.getSegment().getEndFrame(),
phone.toString());
}
}
} else if (null != token) {
// token non-alignable ou non-aligné
if (token.toString().charAt(0)=='[') {
// on traite le cas des commentaires textid
if (token.toString().endsWith("start]")) {
textid2add=token.toString();
textidStard2add=lastFrame; // this value is actually not used; the only important thing is that it is >=0
} else if (token.toString().endsWith("end]")) {
if (textidStard2add<0) {
// only add the textid comment iff there are at least 1 real word in the interval
praatInterval(
wordSB,
wordCount,
lastFrame+1,
lastFrame,
token.toString());
} else {
// cancels the previously started segment, because it is empty
textidStard2add=-1;
}
} else {
// autre commentaire
praatInterval(
wordSB,
wordCount,
lastFrame+1,
lastFrame,
token.toString());
}
} else {
// mot prononcé non aligné (pb d'alignement ?)
praatInterval(
wordSB,
wordCount,
lastFrame,
lastFrame - 1,
token.toString());
}
}// endif token non-alignable
}//for-loop on token
}// while-loop on phrase
// add an empty final intervals if needed
if (lastFrame < frameCount ) {
praatInterval(
wordSB,
wordCount,
lastFrame,
frameCount,
"");
praatInterval(
phoneSB,
phoneCount,
lastFrame,
frameCount,
"");
}
if (withWords) {
praatTierHeader(w, id++, p.getSpeakerName(i) + " words", wordCount[0], frameCount);
w.write(wordSB.toString());
}
if (withPhons) {
praatTierHeader(w, id++, p.getSpeakerName(i) + " phons", phoneCount[0], frameCount);
w.write(phoneSB.toString());
}
}// for-loop on speakers
w.close();
}
public static void praatFileHeader(Appendable w, int frameCount, int tierCount)
throws IOException
{
w.append("File type = \"ooTextFile\"")
.append("\nObject class = \"TextGrid\"")
.append("\n")
.append("\nxmin = 0")
.append("\nxmax = ")
.append(Float.toString(frame2second(frameCount)))
.append("\ntiers? <exists>")
.append("\nsize = ")
.append(Integer.toString(tierCount))
.append("\nitem []:");
}
/**
* Appends a Praat tier header.
* @param w Append text to this writer
* @param id Tier ID (Praat tier numbering starts at 1 and is contiguous!)
* @param name Tier name
* @param intervalCount Number of intervals in the tier
*/
public static void praatTierHeader(
Appendable w, int id, String name, int intervalCount, int frameCount)
throws IOException
{
assert id > 0;
w.append("\n\titem [").append(Integer.toString(id)).append("]:")
.append("\n\t\tclass = \"IntervalTier\"")
.append("\n\t\tname = \"").append(name).append('"') // TODO escape strings
.append("\n\t\txmin = 0")
.append("\n\t\txmax = ")
.append(Float.toString(frame2second(frameCount)))
.append("\n\t\tintervals: size = ")
.append(Integer.toString(intervalCount));
}
/**
* Appends a Praat interval.
* @param w Append text to this writer
* @param id Interval ID (Interval numbering starts at 1 and is contiguous!)
TODO: we use the other praatInterval functions when doing anonymisation... So there must be some mismatch/diff btw both; try and make a single fct !
*/
public static float praatInterval(
Appendable w, int[] id, int xminFrame, int xmaxFrame, String content)
throws IOException
{
float endSec=frame2second(xmaxFrame,false);
float debSec=frame2second(xminFrame,false);
if (debSec>endSec) debSec=endSec;
// STAGE 1 : Check timing consistency with the previous interval (if any)
float lastTime = 0f;
if (id[0]>0) {
String s=w.toString();
int i=s.lastIndexOf("xmax = ");
int j=s.indexOf('\n',i);
lastTime = Float.parseFloat(s.substring(i+7,j));
}
if ( debSec < (lastTime - 0.02) ) {
System.err.println("WARNING: minTime>maxTime "+lastTime+" "+debSec);
} else if ( debSec > (lastTime + 0.02) ) {
// Add empty interval
//System.err.println("WARNING: adding empty interval between "+lastTime+" and "+debSec);
w.append("\n\t\tintervals [").append(Integer.toString(++id[0])).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(lastTime))
.append("\n\t\t\txmax = ")
.append(Float.toString(debSec))
.append("\n\t\t\ttext = \"\"");
} else {
// tiny difference : adjust debSec
//System.err.println("WARNING: adjusting timing from "+debSec+" to "+lastTime);
if (debSec < lastTime) debSec = lastTime;
if (endSec < debSec) endSec = debSec;
}
// STAGE 2 : Add the interval
w.append("\n\t\tintervals [").append(Integer.toString(++id[0])).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(debSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(endSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return endSec;
}
// added this second function because in some cases, we really want the beginning of the next segment to match the end of the previous,
// at the millisecond level !
public static float praatInterval(
Appendable w, int id, float xminSec, int xmaxFrame, String content)
throws IOException
{
float endSec=frame2second(xmaxFrame,false);
w.append("\n\t\tintervals [").append(Integer.toString(id)).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(xminSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(endSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return endSec;
}
public static float praatInterval(
Appendable w, int id, float xminSec, float xmaxSec, String content)
throws IOException
{
w.append("\n\t\tintervals [").append(Integer.toString(id)).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(xminSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(xmaxSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return xmaxSec;
}
}
| synalp/jtrans | src/fr/loria/synalp/jtrans/markup/out/TextGridSaverHelper.java | 3,996 | // wordCount + 1, | line_comment | nl | package fr.loria.synalp.jtrans.markup.out;
import fr.loria.synalp.jtrans.graph.StatePool;
import fr.loria.synalp.jtrans.project.*;
import fr.loria.synalp.jtrans.utils.FileUtils;
import java.io.*;
import java.util.Iterator;
import static fr.loria.synalp.jtrans.utils.FileUtils.getUTF8Writer;
import static fr.loria.synalp.jtrans.speechreco.s4.S4mfccBuffer.frame2second;
public class TextGridSaverHelper {
/**
* If true, anonymized words will be replaced with "*ANON*" and their
* phones will not be shown.
*/
public static enum docensort {withNPs, anonymous, both};
public static docensort censorAnonWords = docensort.both;
protected TextGridSaverHelper() {
// Don't let anyone but subclasses instantiate
}
public static void savePraat(Project p,File f,boolean withWords,boolean withPhons) throws IOException {
if (censorAnonWords==docensort.both) {
String ext="";
String s=f.getAbsolutePath();
int i=s.lastIndexOf('.');
if (i>=0) ext=s.substring(i);
File fanon = new File(FileUtils.noExt(s)+"_anon"+ext);
savePraat(true, p, fanon, withWords, withPhons);
savePraat(false, p, f, withWords, withPhons);
} else if (censorAnonWords==docensort.withNPs) {
savePraat(false, p, f, withWords, withPhons);
} else {
savePraat(true,p, f, withWords, withPhons);
}
}
private static void savePraat(
boolean anonymous,
Project p,
File f,
boolean withWords,
boolean withPhons)
throws IOException
{
Writer w = getUTF8Writer(f);
final int frameCount = (int) p.audioSourceTotalFrames;
praatFileHeader(w,
frameCount,
p.speakerCount() * ((withWords?1:0) + (withPhons?1:0)));
int id = 1;
for (int i = 0; i < p.speakerCount(); i++) {
StringBuilder wordSB = new StringBuilder();
StringBuilder phoneSB = new StringBuilder();
int[] wordCount = {0};
int[] phoneCount = {0};
// frame onto which to tack 0-length elements
int lastFrame = 0;
int textidStard2add = -1; String textid2add = "BUG";
Iterator<Phrase> itr = p.phraseIterator(i);
while (itr.hasNext()) {
Phrase phrase = itr.next();
// frame onto which to tack 0-length elements
if (phrase.getInitialAnchor() != null) {
lastFrame = phrase.getInitialAnchor().getFrame();
}
for (Token token: phrase) {
if (token.isAlignable() && token.isAligned()) {
boolean censored = anonymous && token.shouldBeAnonymized();
String tok = token.shouldBeAnonymized()?"*"+token.toString()+"*":token.toString();
int startWfr = token.getFirstNonSilenceFrame();
int endWfr = token.getLastNonSilenceFrame();
lastFrame = token.getSegment().getEndFrame();
if (startWfr<0) {
// ce n'est que un SIL: j'ajoute un mot pour le SIL
// et bien non, en fait, j'ai decide de ne pas faire apparaitre du tout les SIL dans la tier des mots...
// praatInterval(
// wordSB,
// wordCount +<SUF>
// token.getSegment().getStartFrame(),
// token.getSegment().getEndFrame(),
// censored ? "*ANON*" : tok);
// wordCount++;
} else {
// if (startWfr>token.getSegment().getStartFrame()) {
// // il y a un SIL devant: j'ajoute un mot "SIL" devant
// praatInterval(
// wordSB,
// wordCount + 1,
// token.getSegment().getStartFrame(),
// startWfr,
// StatePool.SILENCE_PHONE);
// wordCount++;
// }
if (textidStard2add>=0) {
// first add a START textid comment with the same frame as the next word
praatInterval(
wordSB,
wordCount,
startWfr,
startWfr-1,
textid2add);
textidStard2add=-1;
}
// cas normal: mot prononcé et aligné
praatInterval(
wordSB,
wordCount,
startWfr,
endWfr,
censored ? "*ANON*" : tok);
lastFrame=endWfr;
// if (endWfr<token.getSegment().getEndFrame()) {
// // il y a un SIL derriere; j'ajoute un mot "SIL" a la fin
// praatInterval(
// wordSB,
// wordCount + 1,
// endWfr,
// token.getSegment().getEndFrame(),
// StatePool.SILENCE_PHONE);
// wordCount++;
// }
}
// dans tous les cas, j'ajoute les phonemes
if (!censored) {
for (Token.Phone phone : token.getPhones()) {
praatInterval(
phoneSB,
phoneCount,
phone.getSegment().getStartFrame(),
phone.getSegment().getEndFrame(),
phone.toString());
}
}
} else if (null != token) {
// token non-alignable ou non-aligné
if (token.toString().charAt(0)=='[') {
// on traite le cas des commentaires textid
if (token.toString().endsWith("start]")) {
textid2add=token.toString();
textidStard2add=lastFrame; // this value is actually not used; the only important thing is that it is >=0
} else if (token.toString().endsWith("end]")) {
if (textidStard2add<0) {
// only add the textid comment iff there are at least 1 real word in the interval
praatInterval(
wordSB,
wordCount,
lastFrame+1,
lastFrame,
token.toString());
} else {
// cancels the previously started segment, because it is empty
textidStard2add=-1;
}
} else {
// autre commentaire
praatInterval(
wordSB,
wordCount,
lastFrame+1,
lastFrame,
token.toString());
}
} else {
// mot prononcé non aligné (pb d'alignement ?)
praatInterval(
wordSB,
wordCount,
lastFrame,
lastFrame - 1,
token.toString());
}
}// endif token non-alignable
}//for-loop on token
}// while-loop on phrase
// add an empty final intervals if needed
if (lastFrame < frameCount ) {
praatInterval(
wordSB,
wordCount,
lastFrame,
frameCount,
"");
praatInterval(
phoneSB,
phoneCount,
lastFrame,
frameCount,
"");
}
if (withWords) {
praatTierHeader(w, id++, p.getSpeakerName(i) + " words", wordCount[0], frameCount);
w.write(wordSB.toString());
}
if (withPhons) {
praatTierHeader(w, id++, p.getSpeakerName(i) + " phons", phoneCount[0], frameCount);
w.write(phoneSB.toString());
}
}// for-loop on speakers
w.close();
}
public static void praatFileHeader(Appendable w, int frameCount, int tierCount)
throws IOException
{
w.append("File type = \"ooTextFile\"")
.append("\nObject class = \"TextGrid\"")
.append("\n")
.append("\nxmin = 0")
.append("\nxmax = ")
.append(Float.toString(frame2second(frameCount)))
.append("\ntiers? <exists>")
.append("\nsize = ")
.append(Integer.toString(tierCount))
.append("\nitem []:");
}
/**
* Appends a Praat tier header.
* @param w Append text to this writer
* @param id Tier ID (Praat tier numbering starts at 1 and is contiguous!)
* @param name Tier name
* @param intervalCount Number of intervals in the tier
*/
public static void praatTierHeader(
Appendable w, int id, String name, int intervalCount, int frameCount)
throws IOException
{
assert id > 0;
w.append("\n\titem [").append(Integer.toString(id)).append("]:")
.append("\n\t\tclass = \"IntervalTier\"")
.append("\n\t\tname = \"").append(name).append('"') // TODO escape strings
.append("\n\t\txmin = 0")
.append("\n\t\txmax = ")
.append(Float.toString(frame2second(frameCount)))
.append("\n\t\tintervals: size = ")
.append(Integer.toString(intervalCount));
}
/**
* Appends a Praat interval.
* @param w Append text to this writer
* @param id Interval ID (Interval numbering starts at 1 and is contiguous!)
TODO: we use the other praatInterval functions when doing anonymisation... So there must be some mismatch/diff btw both; try and make a single fct !
*/
public static float praatInterval(
Appendable w, int[] id, int xminFrame, int xmaxFrame, String content)
throws IOException
{
float endSec=frame2second(xmaxFrame,false);
float debSec=frame2second(xminFrame,false);
if (debSec>endSec) debSec=endSec;
// STAGE 1 : Check timing consistency with the previous interval (if any)
float lastTime = 0f;
if (id[0]>0) {
String s=w.toString();
int i=s.lastIndexOf("xmax = ");
int j=s.indexOf('\n',i);
lastTime = Float.parseFloat(s.substring(i+7,j));
}
if ( debSec < (lastTime - 0.02) ) {
System.err.println("WARNING: minTime>maxTime "+lastTime+" "+debSec);
} else if ( debSec > (lastTime + 0.02) ) {
// Add empty interval
//System.err.println("WARNING: adding empty interval between "+lastTime+" and "+debSec);
w.append("\n\t\tintervals [").append(Integer.toString(++id[0])).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(lastTime))
.append("\n\t\t\txmax = ")
.append(Float.toString(debSec))
.append("\n\t\t\ttext = \"\"");
} else {
// tiny difference : adjust debSec
//System.err.println("WARNING: adjusting timing from "+debSec+" to "+lastTime);
if (debSec < lastTime) debSec = lastTime;
if (endSec < debSec) endSec = debSec;
}
// STAGE 2 : Add the interval
w.append("\n\t\tintervals [").append(Integer.toString(++id[0])).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(debSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(endSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return endSec;
}
// added this second function because in some cases, we really want the beginning of the next segment to match the end of the previous,
// at the millisecond level !
public static float praatInterval(
Appendable w, int id, float xminSec, int xmaxFrame, String content)
throws IOException
{
float endSec=frame2second(xmaxFrame,false);
w.append("\n\t\tintervals [").append(Integer.toString(id)).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(xminSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(endSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return endSec;
}
public static float praatInterval(
Appendable w, int id, float xminSec, float xmaxSec, String content)
throws IOException
{
w.append("\n\t\tintervals [").append(Integer.toString(id)).append("]:")
.append("\n\t\t\txmin = ")
.append(Float.toString(xminSec))
.append("\n\t\t\txmax = ")
.append(Float.toString(xmaxSec))
.append("\n\t\t\ttext = \"").append(content).append('"'); // TODO escape strings
return xmaxSec;
}
}
|
110999_1 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2016 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet
*
*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| syncany/syncany-plugin-gui | core/syncany-lib/src/main/java/org/syncany/operations/up/BlockingTransfersException.java | 290 | /**
* @author Jesse Donkervliet
*
*/ | block_comment | nl | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2016 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet<SUF>*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
|
111029_1 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet
*
*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| syncany/syncany-plugin-s3 | core/syncany-lib/src/main/java/org/syncany/operations/up/BlockingTransfersException.java | 290 | /**
* @author Jesse Donkervliet
*
*/ | block_comment | nl | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet<SUF>*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
|
143180_3 | /*
* 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.jasper;
import java.io.File;
import java.util.Map;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldLocationsCache;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public interface Options {
/**
* Returns true if Jasper issues a compilation error instead of a runtime
* Instantiation error if the class attribute specified in useBean action
* is invalid.
*/
public boolean getErrorOnUseBeanInvalidClassAttribute();
/**
* Are we keeping generated code around?
*/
public boolean getKeepGenerated();
/**
* Returns true if tag handler pooling is enabled, false otherwise.
*/
public boolean isPoolingEnabled();
/**
* Are we supporting HTML mapped servlets?
*/
public boolean getMappedFile();
/**
* Should we include debug information in compiled class?
*/
public boolean getClassDebugInfo();
/**
* Background compile thread check interval in seconds
*/
public int getCheckInterval();
/**
* Is Jasper being used in development mode?
*/
public boolean getDevelopment();
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
public boolean getDisplaySourceFragment();
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
public boolean isSmapSuppressed();
/**
* Indicates whether SMAP info for JSR45 debugging should be dumped to a
* file.
* Ignored if suppressSmap() is true.
*/
public boolean isSmapDumped();
/**
* Should white spaces between directives or actions be trimmed?
*/
public boolean getTrimSpaces();
/**
* Gets the class-id value that is sent to Internet Explorer when using
* <jsp:plugin> tags.
*
* @return Class-id value
*/
public String getIeClassId();
/**
* What is my scratch dir?
*/
public File getScratchDir();
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
public String getClassPath();
/**
* Compiler to use.
*
* <p>
* If <code>null</code> (the default), the java compiler from Eclipse JDT
* project, bundled with Tomcat, will be used. Otherwise, the
* <code>javac</code> task from Apache Ant will be used to call an external
* java compiler and the value of this option will be passed to it. See
* Apache Ant documentation for the possible values.
*/
public String getCompiler();
/**
* The compiler target VM, e.g. 1.1, 1.2, 1.3, 1.4, 1.5 or 1.6.
*/
public String getCompilerTargetVM();
/**
* The compiler source VM, e.g. 1.3, 1.4, 1.5 or 1.6.
*/
public String getCompilerSourceVM();
/**
* Jasper Java compiler class to use.
*/
public String getCompilerClassName();
/**
* The cache for the location of the TLD's
* for the various tag libraries 'exposed'
* by the web application.
* A tag library is 'exposed' either explicitly in
* web.xml or implicitly via the uri tag in the TLD
* of a taglib deployed in a jar file (WEB-INF/lib).
*
* @return the instance of the TldLocationsCache
* for the web-application.
*/
public TldLocationsCache getTldLocationsCache();
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
public String getJavaEncoding();
/**
* The boolean flag to tell Ant whether to fork JSP page compilations.
*
* <p>
* Is used only when Jasper uses an external java compiler (wrapped through
* a <code>javac</code> Apache Ant task).
*/
public boolean getFork();
/**
* Obtain JSP configuration information specified in web.xml.
*/
public JspConfig getJspConfig();
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
public boolean isXpoweredBy();
/**
* Obtain a Tag Plugin Manager
*/
public TagPluginManager getTagPluginManager();
/**
* Indicates whether text strings are to be generated as char arrays.
*
* @return <code>true</code> if text strings are to be generated as char
* arrays, <code>false</code> otherwise
*/
public boolean genStringAsCharArray();
/**
* Modification test interval.
*/
public int getModificationTestInterval();
/**
* Re-compile on failure.
*/
public boolean getRecompileOnFail();
/**
* Is caching enabled (used for precompilation).
*/
public boolean isCaching();
/**
* The web-application wide cache for the TagLibraryInfo tag library
* descriptors, used if {@link #isCaching()} returns <code>true</code>.
*
* <p>
* Using this cache avoids the cost of repeating the parsing of a tag
* library descriptor XML file (performed by TagLibraryInfoImpl.parseTLD).
* </p>
*
* @return the Map(String uri, TagLibraryInfo tld) instance.
*/
public Map<String, TagLibraryInfo> getCache();
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded. If unset or less than 0, no jsps
* are unloaded.
*/
public int getMaxLoadedJsps();
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
public int getJspIdleTimeout();
}
| szlike/tomcat-ttc-everything | java/org/apache/jasper/Options.java | 2,018 | /**
* Are we keeping generated code around?
*/ | 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.jasper;
import java.io.File;
import java.util.Map;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldLocationsCache;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public interface Options {
/**
* Returns true if Jasper issues a compilation error instead of a runtime
* Instantiation error if the class attribute specified in useBean action
* is invalid.
*/
public boolean getErrorOnUseBeanInvalidClassAttribute();
/**
* Are we keeping<SUF>*/
public boolean getKeepGenerated();
/**
* Returns true if tag handler pooling is enabled, false otherwise.
*/
public boolean isPoolingEnabled();
/**
* Are we supporting HTML mapped servlets?
*/
public boolean getMappedFile();
/**
* Should we include debug information in compiled class?
*/
public boolean getClassDebugInfo();
/**
* Background compile thread check interval in seconds
*/
public int getCheckInterval();
/**
* Is Jasper being used in development mode?
*/
public boolean getDevelopment();
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
public boolean getDisplaySourceFragment();
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
public boolean isSmapSuppressed();
/**
* Indicates whether SMAP info for JSR45 debugging should be dumped to a
* file.
* Ignored if suppressSmap() is true.
*/
public boolean isSmapDumped();
/**
* Should white spaces between directives or actions be trimmed?
*/
public boolean getTrimSpaces();
/**
* Gets the class-id value that is sent to Internet Explorer when using
* <jsp:plugin> tags.
*
* @return Class-id value
*/
public String getIeClassId();
/**
* What is my scratch dir?
*/
public File getScratchDir();
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
public String getClassPath();
/**
* Compiler to use.
*
* <p>
* If <code>null</code> (the default), the java compiler from Eclipse JDT
* project, bundled with Tomcat, will be used. Otherwise, the
* <code>javac</code> task from Apache Ant will be used to call an external
* java compiler and the value of this option will be passed to it. See
* Apache Ant documentation for the possible values.
*/
public String getCompiler();
/**
* The compiler target VM, e.g. 1.1, 1.2, 1.3, 1.4, 1.5 or 1.6.
*/
public String getCompilerTargetVM();
/**
* The compiler source VM, e.g. 1.3, 1.4, 1.5 or 1.6.
*/
public String getCompilerSourceVM();
/**
* Jasper Java compiler class to use.
*/
public String getCompilerClassName();
/**
* The cache for the location of the TLD's
* for the various tag libraries 'exposed'
* by the web application.
* A tag library is 'exposed' either explicitly in
* web.xml or implicitly via the uri tag in the TLD
* of a taglib deployed in a jar file (WEB-INF/lib).
*
* @return the instance of the TldLocationsCache
* for the web-application.
*/
public TldLocationsCache getTldLocationsCache();
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
public String getJavaEncoding();
/**
* The boolean flag to tell Ant whether to fork JSP page compilations.
*
* <p>
* Is used only when Jasper uses an external java compiler (wrapped through
* a <code>javac</code> Apache Ant task).
*/
public boolean getFork();
/**
* Obtain JSP configuration information specified in web.xml.
*/
public JspConfig getJspConfig();
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
public boolean isXpoweredBy();
/**
* Obtain a Tag Plugin Manager
*/
public TagPluginManager getTagPluginManager();
/**
* Indicates whether text strings are to be generated as char arrays.
*
* @return <code>true</code> if text strings are to be generated as char
* arrays, <code>false</code> otherwise
*/
public boolean genStringAsCharArray();
/**
* Modification test interval.
*/
public int getModificationTestInterval();
/**
* Re-compile on failure.
*/
public boolean getRecompileOnFail();
/**
* Is caching enabled (used for precompilation).
*/
public boolean isCaching();
/**
* The web-application wide cache for the TagLibraryInfo tag library
* descriptors, used if {@link #isCaching()} returns <code>true</code>.
*
* <p>
* Using this cache avoids the cost of repeating the parsing of a tag
* library descriptor XML file (performed by TagLibraryInfoImpl.parseTLD).
* </p>
*
* @return the Map(String uri, TagLibraryInfo tld) instance.
*/
public Map<String, TagLibraryInfo> getCache();
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded. If unset or less than 0, no jsps
* are unloaded.
*/
public int getMaxLoadedJsps();
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
public int getJspIdleTimeout();
}
|
169763_3 | package com.example.novi_be10_techiteasy.controllers;
import com.example.novi_be10_techiteasy.exceptions.RecordNotFoundException;
import com.example.novi_be10_techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
//annotaties exceptioncontroller class
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = RecordNotFoundException.class)//exception controllermethod basisopdracht
public ResponseEntity<Object> exception(RecordNotFoundException exception)
{
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
}
//bonus opdracht B6: out of bounds exception. deze vangt de standaard Java index-out-of-bounds error op en geeft een http statuscode terug in een responseentity ipv de console melding.
@ExceptionHandler(value = IndexOutOfBoundsException.class)
public ResponseEntity<Object> exception(IndexOutOfBoundsException exception){
return new ResponseEntity<>("Dit id bestaat niet",HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = TelevisionNameTooLongException.class)//bonus bonus opdracht 1 hiervoor maken we zelf de exception class in het exceptionmapje.
public ResponseEntity<String> exception(TelevisionNameTooLongException exception){
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
}
| szuiderweg/be-hw-techiteasy | src/main/java/com/example/novi_be10_techiteasy/controllers/ExceptionController.java | 409 | //bonus bonus opdracht 1 hiervoor maken we zelf de exception class in het exceptionmapje. | line_comment | nl | package com.example.novi_be10_techiteasy.controllers;
import com.example.novi_be10_techiteasy.exceptions.RecordNotFoundException;
import com.example.novi_be10_techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
//annotaties exceptioncontroller class
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = RecordNotFoundException.class)//exception controllermethod basisopdracht
public ResponseEntity<Object> exception(RecordNotFoundException exception)
{
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
}
//bonus opdracht B6: out of bounds exception. deze vangt de standaard Java index-out-of-bounds error op en geeft een http statuscode terug in een responseentity ipv de console melding.
@ExceptionHandler(value = IndexOutOfBoundsException.class)
public ResponseEntity<Object> exception(IndexOutOfBoundsException exception){
return new ResponseEntity<>("Dit id bestaat niet",HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = TelevisionNameTooLongException.class)//bonus bonus<SUF>
public ResponseEntity<String> exception(TelevisionNameTooLongException exception){
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
}
|
7730_30 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.menu;
import org.mozilla.gecko.R;
import org.mozilla.gecko.widget.Divider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.ActionProvider;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends ListView
implements Menu,
MenuItem.OnMenuItemClickListener,
AdapterView.OnItemClickListener,
GeckoMenuItem.OnVisibilityChangedListener,
GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
/*
* A callback for a menu item selected event.
*/
public static interface Callback {
// Called when a menu item is selected, with the actual menu item as the argument.
public boolean onMenuItemSelected(MenuItem item);
}
/*
* An interface for a presenter to show the menu.
* Either an Activity or a View can be a presenter, that can watch for events
* and show/hide menu.
*/
public static interface MenuPresenter {
// Open the menu.
public void openMenu();
// Show the actual view contaning the menu items. This can either be a parent or sub-menu.
public void showMenu(View menu);
// Close the menu.
public void closeMenu();
}
/*
* An interface for a presenter of action-items.
* Either an Activity or a View can be a presenter, that can watch for events
* and add/remove action-items. If not ActionItemBarPresenter, the menu uses a
* DefaultActionItemBarPresenter, that shows the action-items as a header over list-view.
*/
public static interface ActionItemBarPresenter {
// Add an action-item.
public void addActionItem(View actionItem);
// Remove an action-item based on the index. The index used while adding.
public void removeActionItem(int index);
// Get the number of action-items shown by the presenter.
public int getActionItemsCount();
}
protected static final int NO_ID = 0;
// List of all menu items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to a callback for menu events.
private Callback mCallback;
// Reference to menu presenter.
private MenuPresenter mMenuPresenter;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
// Adapter to hold the list of menu items.
private MenuItemsAdapter mAdapter;
// ActionBar to show the menu items as icons.
private LinearLayout mActionBar;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Add a header view that acts as an action-bar.
mActionBar = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.menu_action_bar, null);
// Attach an adapter.
mAdapter = new MenuItemsAdapter(context);
setAdapter(mAdapter);
setOnItemClickListener(this);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
mActionItemBarPresenter = new DefaultActionItemBarPresenter(mContext, mActionBar);
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(this);
menuItem.setOnMenuItemClickListener(this);
mAdapter.addMenuItem(menuItem);
mItems.add(menuItem);
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(null);
menuItem.setOnMenuItemClickListener(this);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before adding the header view to a list.
setAdapter(null);
addHeaderView(mActionBar);
setAdapter(mAdapter);
}
mActionItems.add(menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
mItems.add(menuItem);
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
MenuItem menuItem = add(groupId, itemId, order, title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
MenuItem menuItem = add(groupId, itemId, order, titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
MenuItem menuItem = add(title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int titleRes) {
MenuItem menuItem = add(titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public void clear() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
SubMenu subMenu = menuItem.getSubMenu();
subMenu.clear();
}
}
mAdapter.clear();
mItems.clear();
mActionItems.clear();
}
@Override
public void close() {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
return menuItem;
} else if (menuItem.hasSubMenu()) {
if (menuItem.getActionProvider() == null) {
SubMenu subMenu = menuItem.getSubMenu();
MenuItem item = subMenu.findItem(id);
if (item != null)
return item;
}
}
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
GeckoMenuItem item = (GeckoMenuItem) findItem(id);
if (item != null) {
if (mActionItems.contains(item)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(item));
mActionItems.remove(item);
mItems.remove(item);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before removing the header view from a list.
setAdapter(null);
removeHeaderView(mActionBar);
setAdapter(mAdapter);
}
return;
}
mAdapter.removeMenuItem(item);
mItems.remove(item);
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
@Override
public void onVisibilityChanged(GeckoMenuItem item, boolean isVisible) {
if (isVisible)
mAdapter.addMenuItem(item);
else
mAdapter.removeMenuItem(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position -= getHeaderViewsCount();
GeckoMenuItem item = mAdapter.getItem(position);
if (item.isEnabled())
item.onClick(item.getLayout());
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!item.hasSubMenu()) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return mCallback.onMenuItemSelected(item);
} else {
// Refresh the submenu for the provider.
ActionProvider provider = item.getActionProvider();
if (provider != null) {
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
provider.onPrepareSubMenu(subMenu);
((GeckoMenuItem) item).setSubMenu(subMenu);
}
// Show the submenu.
if (mMenuPresenter != null)
mMenuPresenter.showMenu((GeckoSubMenu) item.getSubMenu());
return true;
}
}
public boolean onCustomMenuItemClick(MenuItem item, MenuItem.OnMenuItemClickListener listener) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return listener.onMenuItemClick(item);
}
public Callback getCallback() {
return mCallback;
}
public MenuPresenter getMenuPresenter() {
return mMenuPresenter;
}
public void setCallback(Callback callback) {
mCallback = callback;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setCallback(mCallback);
}
}
}
public void setMenuPresenter(MenuPresenter presenter) {
mMenuPresenter = presenter;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setMenuPresenter(mMenuPresenter);
}
}
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
// Action Items are added to the header view by default.
// URL bar can register itself as a presenter, in case it has a different place to show them.
private class DefaultActionItemBarPresenter implements ActionItemBarPresenter {
private Context mContext;
private LinearLayout mContainer;
private List<View> mItems;
public DefaultActionItemBarPresenter(Context context, LinearLayout container) {
mContext = context;
mContainer = container;
mItems = new ArrayList<View>();
}
@Override
public void addActionItem(View actionItem) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(actionItem.getLayoutParams());
params.weight = 1.0f;
actionItem.setLayoutParams(params);
if (mItems.size() > 0) {
Divider divider = new Divider(mContext, null);
divider.setOrientation(Divider.Orientation.VERTICAL);
divider.setBackgroundColor(0xFFD1D5DA);
mContainer.addView(divider);
}
mContainer.addView(actionItem);
mItems.add(actionItem);
}
@Override
public void removeActionItem(int index) {
// Remove the icon and the vertical divider.
mContainer.removeViewAt(index * 2);
if (index != 0)
mContainer.removeViewAt(index * 2 - 1);
mItems.remove(index);
if (mItems.size() == 0)
mContainer.setVisibility(View.GONE);
}
@Override
public int getActionItemsCount() {
return mItems.size();
}
}
// Adapter to bind menu items to the list.
private class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private List<GeckoMenuItem> mItems;
public MenuItemsAdapter(Context context) {
mContext = context;
mItems = new ArrayList<GeckoMenuItem>();
}
@Override
public int getCount() {
return (mItems == null ? 0 : mItems.size());
}
@Override
public GeckoMenuItem getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return mItems.get(position).getLayout();
}
@Override
public int getItemViewType (int position) {
return AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public boolean areAllItemsEnabled() {
for (GeckoMenuItem item : mItems) {
if (!item.isEnabled())
return false;
}
return true;
}
@Override
public boolean isEnabled(int position) {
return getItem(position).isEnabled();
}
public void addMenuItem(GeckoMenuItem menuItem) {
if (mItems.contains(menuItem))
return;
// Insert it in proper order.
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
notifyDataSetChanged();
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
notifyDataSetChanged();
}
public void removeMenuItem(GeckoMenuItem menuItem) {
// Remove it from the list.
mItems.remove(menuItem);
notifyDataSetChanged();
}
public void clear() {
mItems.clear();
notifyDataSetChanged();
}
public GeckoMenuItem getMenuItem(int id) {
for (GeckoMenuItem item : mItems) {
if (item.getItemId() == id)
return item;
}
return null;
}
}
}
| t32k/mozilla-central | mobile/android/base/menu/GeckoMenu.java | 4,916 | // Insert it in proper order. | line_comment | nl | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.menu;
import org.mozilla.gecko.R;
import org.mozilla.gecko.widget.Divider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.ActionProvider;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends ListView
implements Menu,
MenuItem.OnMenuItemClickListener,
AdapterView.OnItemClickListener,
GeckoMenuItem.OnVisibilityChangedListener,
GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
/*
* A callback for a menu item selected event.
*/
public static interface Callback {
// Called when a menu item is selected, with the actual menu item as the argument.
public boolean onMenuItemSelected(MenuItem item);
}
/*
* An interface for a presenter to show the menu.
* Either an Activity or a View can be a presenter, that can watch for events
* and show/hide menu.
*/
public static interface MenuPresenter {
// Open the menu.
public void openMenu();
// Show the actual view contaning the menu items. This can either be a parent or sub-menu.
public void showMenu(View menu);
// Close the menu.
public void closeMenu();
}
/*
* An interface for a presenter of action-items.
* Either an Activity or a View can be a presenter, that can watch for events
* and add/remove action-items. If not ActionItemBarPresenter, the menu uses a
* DefaultActionItemBarPresenter, that shows the action-items as a header over list-view.
*/
public static interface ActionItemBarPresenter {
// Add an action-item.
public void addActionItem(View actionItem);
// Remove an action-item based on the index. The index used while adding.
public void removeActionItem(int index);
// Get the number of action-items shown by the presenter.
public int getActionItemsCount();
}
protected static final int NO_ID = 0;
// List of all menu items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to a callback for menu events.
private Callback mCallback;
// Reference to menu presenter.
private MenuPresenter mMenuPresenter;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
// Adapter to hold the list of menu items.
private MenuItemsAdapter mAdapter;
// ActionBar to show the menu items as icons.
private LinearLayout mActionBar;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Add a header view that acts as an action-bar.
mActionBar = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.menu_action_bar, null);
// Attach an adapter.
mAdapter = new MenuItemsAdapter(context);
setAdapter(mAdapter);
setOnItemClickListener(this);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
mActionItemBarPresenter = new DefaultActionItemBarPresenter(mContext, mActionBar);
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(this);
menuItem.setOnMenuItemClickListener(this);
mAdapter.addMenuItem(menuItem);
mItems.add(menuItem);
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setMenu(this);
menuItem.setOnShowAsActionChangedListener(this);
menuItem.setOnVisibilityChangedListener(null);
menuItem.setOnMenuItemClickListener(this);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before adding the header view to a list.
setAdapter(null);
addHeaderView(mActionBar);
setAdapter(mAdapter);
}
mActionItems.add(menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
mItems.add(menuItem);
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
MenuItem menuItem = add(groupId, itemId, order, title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
MenuItem menuItem = add(groupId, itemId, order, titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
MenuItem menuItem = add(title);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public SubMenu addSubMenu(int titleRes) {
MenuItem menuItem = add(titleRes);
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
subMenu.setMenuItem(menuItem);
subMenu.setCallback(mCallback);
subMenu.setMenuPresenter(mMenuPresenter);
((GeckoMenuItem) menuItem).setSubMenu(subMenu);
return subMenu;
}
@Override
public void clear() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
SubMenu subMenu = menuItem.getSubMenu();
subMenu.clear();
}
}
mAdapter.clear();
mItems.clear();
mActionItems.clear();
}
@Override
public void close() {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
return menuItem;
} else if (menuItem.hasSubMenu()) {
if (menuItem.getActionProvider() == null) {
SubMenu subMenu = menuItem.getSubMenu();
MenuItem item = subMenu.findItem(id);
if (item != null)
return item;
}
}
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
GeckoMenuItem item = (GeckoMenuItem) findItem(id);
if (item != null) {
if (mActionItems.contains(item)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(item));
mActionItems.remove(item);
mItems.remove(item);
if (mActionItems.size() == 0 &&
mActionItemBarPresenter instanceof DefaultActionItemBarPresenter) {
// Reset the adapter before removing the header view from a list.
setAdapter(null);
removeHeaderView(mActionBar);
setAdapter(mAdapter);
}
return;
}
mAdapter.removeMenuItem(item);
mItems.remove(item);
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
@Override
public void onVisibilityChanged(GeckoMenuItem item, boolean isVisible) {
if (isVisible)
mAdapter.addMenuItem(item);
else
mAdapter.removeMenuItem(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position -= getHeaderViewsCount();
GeckoMenuItem item = mAdapter.getItem(position);
if (item.isEnabled())
item.onClick(item.getLayout());
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!item.hasSubMenu()) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return mCallback.onMenuItemSelected(item);
} else {
// Refresh the submenu for the provider.
ActionProvider provider = item.getActionProvider();
if (provider != null) {
GeckoSubMenu subMenu = new GeckoSubMenu(mContext, null);
provider.onPrepareSubMenu(subMenu);
((GeckoMenuItem) item).setSubMenu(subMenu);
}
// Show the submenu.
if (mMenuPresenter != null)
mMenuPresenter.showMenu((GeckoSubMenu) item.getSubMenu());
return true;
}
}
public boolean onCustomMenuItemClick(MenuItem item, MenuItem.OnMenuItemClickListener listener) {
if (mMenuPresenter != null)
mMenuPresenter.closeMenu();
return listener.onMenuItemClick(item);
}
public Callback getCallback() {
return mCallback;
}
public MenuPresenter getMenuPresenter() {
return mMenuPresenter;
}
public void setCallback(Callback callback) {
mCallback = callback;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setCallback(mCallback);
}
}
}
public void setMenuPresenter(MenuPresenter presenter) {
mMenuPresenter = presenter;
// Update the submenus just in case this changes on the fly.
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.hasSubMenu()) {
GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu();
subMenu.setMenuPresenter(mMenuPresenter);
}
}
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
// Action Items are added to the header view by default.
// URL bar can register itself as a presenter, in case it has a different place to show them.
private class DefaultActionItemBarPresenter implements ActionItemBarPresenter {
private Context mContext;
private LinearLayout mContainer;
private List<View> mItems;
public DefaultActionItemBarPresenter(Context context, LinearLayout container) {
mContext = context;
mContainer = container;
mItems = new ArrayList<View>();
}
@Override
public void addActionItem(View actionItem) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(actionItem.getLayoutParams());
params.weight = 1.0f;
actionItem.setLayoutParams(params);
if (mItems.size() > 0) {
Divider divider = new Divider(mContext, null);
divider.setOrientation(Divider.Orientation.VERTICAL);
divider.setBackgroundColor(0xFFD1D5DA);
mContainer.addView(divider);
}
mContainer.addView(actionItem);
mItems.add(actionItem);
}
@Override
public void removeActionItem(int index) {
// Remove the icon and the vertical divider.
mContainer.removeViewAt(index * 2);
if (index != 0)
mContainer.removeViewAt(index * 2 - 1);
mItems.remove(index);
if (mItems.size() == 0)
mContainer.setVisibility(View.GONE);
}
@Override
public int getActionItemsCount() {
return mItems.size();
}
}
// Adapter to bind menu items to the list.
private class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private List<GeckoMenuItem> mItems;
public MenuItemsAdapter(Context context) {
mContext = context;
mItems = new ArrayList<GeckoMenuItem>();
}
@Override
public int getCount() {
return (mItems == null ? 0 : mItems.size());
}
@Override
public GeckoMenuItem getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return mItems.get(position).getLayout();
}
@Override
public int getItemViewType (int position) {
return AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public boolean areAllItemsEnabled() {
for (GeckoMenuItem item : mItems) {
if (!item.isEnabled())
return false;
}
return true;
}
@Override
public boolean isEnabled(int position) {
return getItem(position).isEnabled();
}
public void addMenuItem(GeckoMenuItem menuItem) {
if (mItems.contains(menuItem))
return;
// Insert it<SUF>
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
notifyDataSetChanged();
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
notifyDataSetChanged();
}
public void removeMenuItem(GeckoMenuItem menuItem) {
// Remove it from the list.
mItems.remove(menuItem);
notifyDataSetChanged();
}
public void clear() {
mItems.clear();
notifyDataSetChanged();
}
public GeckoMenuItem getMenuItem(int id) {
for (GeckoMenuItem item : mItems) {
if (item.getItemId() == id)
return item;
}
return null;
}
}
}
|
142842_10 | //------------------------------------------------------------------------------
// Copyright (c) 2010 Carnegie Institution for Science. All rights reserved.
// $Revision: 1.11 $
// $Date: 2004/04/05 22:43:46 $
//------------------------------------------------------------------------------
package org.tair.querytools;
import org.tair.utilities.*;
import org.tair.tfc.*;
import java.sql.*;
import java.io.*;
import java.util.*;
/**
* RestrictionEnzymeDetail is a composite class to represent all information
* associated with an entry in the restriction enzyme table.
* RestrictionEnzymeDetail contains an instance of
* <code>TfcRestrictionEnzyme</code> in addition to all information in
* <code>TairObjectDetail</code> superclass.
*
* <p>
* RestrictionEnzymeDetail overrides the getElementType() method implemented
* in TairObjectDetail to satisfy Accessible interface so that a type specific
* element type can be returned.
*/
public class RestrictionEnzymeDetail extends TairObjectDetail {
private TfcRestrictionEnzyme restrictionEnzyme;
/**
* Creates an empty instance of RestrictionEnzymeDetail
*/
public RestrictionEnzymeDetail() { }
/**
* Creates an instance of RestrictionEnzymeDetail to reflect data referenced
* by submitted restriction_enzyme_id
*
* @param conn An active connection to the database
* @param restriction_enzyme_id Restriction enzyme id to retrieve data for
* @throws SQLException if a database error occurs
*/
public RestrictionEnzymeDetail( DBconnection conn,
Long restriction_enzyme_id )
throws SQLException {
get_information( conn, restriction_enzyme_id );
}
/**
* Creates an instance of RestrictionEnzymeDetail to reflect data referenced
* by submitted restriction_enzyme name
*
* @param conn An active connection to the database
* @param name Restriction enzyme name to retrieve data for
* @throws SQLException if a database error occurs
*/
public RestrictionEnzymeDetail( DBconnection conn, String name )
throws SQLException {
if ( name != null ) {
get_information( conn, name );
}
}
//
// TfcRestrictionEnzyme wrappers
//
public String get_name() {
return restrictionEnzyme.get_name();
}
public String get_site() {
return restrictionEnzyme.get_site();
}
public String get_cleavage() {
return restrictionEnzyme.get_cleavage();
}
public String get_isoschizomer() {
return restrictionEnzyme.get_isoschizomer();
}
public Integer get_offset() {
return restrictionEnzyme.get_offset();
}
public Integer get_overhang() {
return restrictionEnzyme.get_overhang();
}
public java.util.Date get_date_last_modified() {
return restrictionEnzyme.get_date_last_modified();
}
public java.util.Date get_date_entered() {
return restrictionEnzyme.get_date_entered();
}
public String get_original_name() {
return restrictionEnzyme.get_original_name();
}
/**
* Retrieves data for submitted restriction enzyme id
*
* @param conn An active connection to the database
* @param restriction_enzyme_id Restriction enzyme id to retrieve data for
* @throws SQLException if a database error occurs
*/
public void get_information( DBconnection conn,
Long restriction_enzyme_id )
throws SQLException {
restrictionEnzyme = new TfcRestrictionEnzyme( conn,
restriction_enzyme_id );
// populate superclass data
super.populateBaseObject( restrictionEnzyme );
getTairObjectInformation( conn );
}
/**
* Retrieves data for submitted restriction enzyme name
*
* @param conn An active connection to the database
* @param name Restriction enzyme name to retrieve data for
* @throws SQLException if a database error occurs
*/
public void get_information( DBconnection conn, String name )
throws SQLException {
if ( name != null ) {
get_information( conn, get_id( conn, name ) );
}
}
// get restriction enzyme id given name
private Long get_id( DBconnection conn, String name ) throws SQLException {
Long id = null;
ResultSet results = null;
String query =
"SELECT restriction_enzyme_id " +
"FROM RestrictionEnzyme " +
"WHERE name = " +
TextConverter.dbQuote( name );
conn.setQuery( query );
results = conn.getResultSet();
if ( results.next() ) {
id = new Long( results.getLong( "restriction_enzyme_id" ) );
}
conn.releaseResources();
return id;
}
/**
* Retrieves element type of this object for use in creating TAIR accession
* number. Implemented here to satisfy the <code>Accessible</code> interface
*
* @return Object's element type (restrictionenzyme) for use in creating
* TAIR accession
*/
public final String getElementType() {
return "restrictionenzyme";
}
/**
* For unit testing only
*/
public void test() {
super.test();
System.out.println( "*** RestrictionEnzymeDetail content test **" );
restrictionEnzyme.test();
System.out.println( "*** RestrictionEnzymeDetail content test end **" );
}
/**
* For unit testing only
*/
public static void main( String[] args ) {
try {
DBconnection connection = new DBconnection();
Long test_id = new Long( 60 );
RestrictionEnzymeDetail restriction_enzyme =
new RestrictionEnzymeDetail( connection, test_id );
restriction_enzyme.test();
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
| tair/tairwebapp | src/org/tair/querytools/RestrictionEnzymeDetail.java | 1,682 | // get restriction enzyme id given name | line_comment | nl | //------------------------------------------------------------------------------
// Copyright (c) 2010 Carnegie Institution for Science. All rights reserved.
// $Revision: 1.11 $
// $Date: 2004/04/05 22:43:46 $
//------------------------------------------------------------------------------
package org.tair.querytools;
import org.tair.utilities.*;
import org.tair.tfc.*;
import java.sql.*;
import java.io.*;
import java.util.*;
/**
* RestrictionEnzymeDetail is a composite class to represent all information
* associated with an entry in the restriction enzyme table.
* RestrictionEnzymeDetail contains an instance of
* <code>TfcRestrictionEnzyme</code> in addition to all information in
* <code>TairObjectDetail</code> superclass.
*
* <p>
* RestrictionEnzymeDetail overrides the getElementType() method implemented
* in TairObjectDetail to satisfy Accessible interface so that a type specific
* element type can be returned.
*/
public class RestrictionEnzymeDetail extends TairObjectDetail {
private TfcRestrictionEnzyme restrictionEnzyme;
/**
* Creates an empty instance of RestrictionEnzymeDetail
*/
public RestrictionEnzymeDetail() { }
/**
* Creates an instance of RestrictionEnzymeDetail to reflect data referenced
* by submitted restriction_enzyme_id
*
* @param conn An active connection to the database
* @param restriction_enzyme_id Restriction enzyme id to retrieve data for
* @throws SQLException if a database error occurs
*/
public RestrictionEnzymeDetail( DBconnection conn,
Long restriction_enzyme_id )
throws SQLException {
get_information( conn, restriction_enzyme_id );
}
/**
* Creates an instance of RestrictionEnzymeDetail to reflect data referenced
* by submitted restriction_enzyme name
*
* @param conn An active connection to the database
* @param name Restriction enzyme name to retrieve data for
* @throws SQLException if a database error occurs
*/
public RestrictionEnzymeDetail( DBconnection conn, String name )
throws SQLException {
if ( name != null ) {
get_information( conn, name );
}
}
//
// TfcRestrictionEnzyme wrappers
//
public String get_name() {
return restrictionEnzyme.get_name();
}
public String get_site() {
return restrictionEnzyme.get_site();
}
public String get_cleavage() {
return restrictionEnzyme.get_cleavage();
}
public String get_isoschizomer() {
return restrictionEnzyme.get_isoschizomer();
}
public Integer get_offset() {
return restrictionEnzyme.get_offset();
}
public Integer get_overhang() {
return restrictionEnzyme.get_overhang();
}
public java.util.Date get_date_last_modified() {
return restrictionEnzyme.get_date_last_modified();
}
public java.util.Date get_date_entered() {
return restrictionEnzyme.get_date_entered();
}
public String get_original_name() {
return restrictionEnzyme.get_original_name();
}
/**
* Retrieves data for submitted restriction enzyme id
*
* @param conn An active connection to the database
* @param restriction_enzyme_id Restriction enzyme id to retrieve data for
* @throws SQLException if a database error occurs
*/
public void get_information( DBconnection conn,
Long restriction_enzyme_id )
throws SQLException {
restrictionEnzyme = new TfcRestrictionEnzyme( conn,
restriction_enzyme_id );
// populate superclass data
super.populateBaseObject( restrictionEnzyme );
getTairObjectInformation( conn );
}
/**
* Retrieves data for submitted restriction enzyme name
*
* @param conn An active connection to the database
* @param name Restriction enzyme name to retrieve data for
* @throws SQLException if a database error occurs
*/
public void get_information( DBconnection conn, String name )
throws SQLException {
if ( name != null ) {
get_information( conn, get_id( conn, name ) );
}
}
// get restriction<SUF>
private Long get_id( DBconnection conn, String name ) throws SQLException {
Long id = null;
ResultSet results = null;
String query =
"SELECT restriction_enzyme_id " +
"FROM RestrictionEnzyme " +
"WHERE name = " +
TextConverter.dbQuote( name );
conn.setQuery( query );
results = conn.getResultSet();
if ( results.next() ) {
id = new Long( results.getLong( "restriction_enzyme_id" ) );
}
conn.releaseResources();
return id;
}
/**
* Retrieves element type of this object for use in creating TAIR accession
* number. Implemented here to satisfy the <code>Accessible</code> interface
*
* @return Object's element type (restrictionenzyme) for use in creating
* TAIR accession
*/
public final String getElementType() {
return "restrictionenzyme";
}
/**
* For unit testing only
*/
public void test() {
super.test();
System.out.println( "*** RestrictionEnzymeDetail content test **" );
restrictionEnzyme.test();
System.out.println( "*** RestrictionEnzymeDetail content test end **" );
}
/**
* For unit testing only
*/
public static void main( String[] args ) {
try {
DBconnection connection = new DBconnection();
Long test_id = new Long( 60 );
RestrictionEnzymeDetail restriction_enzyme =
new RestrictionEnzymeDetail( connection, test_id );
restriction_enzyme.test();
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
|
101655_4 | public class Player{
private String name;
private int hp;
private int attackPower;
private int defense;
public Player (String name, int defense){
this.name = name;
this.defense = defense;
hp = 100;
}
//lengkapi
public Player (String name, int attack, int defense){
this.name = name;
attackPower = attack;
this.defense = defense;
hp = 100;
}
// public int PDamage(Player enemy){
// int darah = 0;
// if(defense - enemy.getAttackPower() >= 0 ){
// darah = (defense - enemy.getAttackPower());
// }else if(defense - enemy.getAttackPower() < 0){
// darah = -1*(defense - enemy.getAttackPower());
// }
// return darah;
// }
public void getDamage(Player enemy){
//hp = hp - PDamage(enemy);
if(defense < enemy.getAttackPower()){
hp = hp - Math.abs(defense - enemy.getAttackPower());
}
}
public void status(){
System.out.println(name + " status");
if(hp < 0){
System.out.println("mati");
}else{
System.out.println("Hp = " + hp);
}
System.out.println("Defense = " + defense);
System.out.println("Attack = " + attackPower);
System.out.println();
}
//lengkapi
public void setAttackPower(int attackPower){
this.attackPower = attackPower;
}
public int getAttackPower(){
return attackPower;
}
public static void main(String[] args) {
int defense = 0;
int attack = 0;
//int attack2 = 35;
Player player1 = new Player("Mino", attack, defense);
Player player2 = new Player("Hilda", defense);
player2.setAttackPower(0);
player1.getDamage(player2);
player2.getDamage(player1);
player1.status();
player2.status();
}
} | takdim/repost | latihanOOP/tugas praktikum/tugasPraktikum2/Player.java | 619 | // }else if(defense - enemy.getAttackPower() < 0){
| line_comment | nl | public class Player{
private String name;
private int hp;
private int attackPower;
private int defense;
public Player (String name, int defense){
this.name = name;
this.defense = defense;
hp = 100;
}
//lengkapi
public Player (String name, int attack, int defense){
this.name = name;
attackPower = attack;
this.defense = defense;
hp = 100;
}
// public int PDamage(Player enemy){
// int darah = 0;
// if(defense - enemy.getAttackPower() >= 0 ){
// darah = (defense - enemy.getAttackPower());
// }else if(defense<SUF>
// darah = -1*(defense - enemy.getAttackPower());
// }
// return darah;
// }
public void getDamage(Player enemy){
//hp = hp - PDamage(enemy);
if(defense < enemy.getAttackPower()){
hp = hp - Math.abs(defense - enemy.getAttackPower());
}
}
public void status(){
System.out.println(name + " status");
if(hp < 0){
System.out.println("mati");
}else{
System.out.println("Hp = " + hp);
}
System.out.println("Defense = " + defense);
System.out.println("Attack = " + attackPower);
System.out.println();
}
//lengkapi
public void setAttackPower(int attackPower){
this.attackPower = attackPower;
}
public int getAttackPower(){
return attackPower;
}
public static void main(String[] args) {
int defense = 0;
int attack = 0;
//int attack2 = 35;
Player player1 = new Player("Mino", attack, defense);
Player player2 = new Player("Hilda", defense);
player2.setAttackPower(0);
player1.getDamage(player2);
player2.getDamage(player1);
player1.status();
player2.status();
}
} |
75609_1 | package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors;
import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2;
import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.phase.Phase;
/**
* Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt
* en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de
* {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de
* UWLR afspraak.
*/
public class FaultInterceptor extends AbstractSoapInterceptor {
public FaultInterceptor() {
super(Phase.PRE_LOGICAL);
}
@Override
public void handleMessage(final SoapMessage message) {
// Kijk of in de message een Exception verpakt zit
Object exception = message.getContent(Exception.class);
// Als er een exception is die niet van het type SoapFault is, dan moet deze
// vertaald worden naar een SoapFault.
if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault)))
message.setContent(
Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause()));
}
}
| takirchjunger/uwlr-client-server | src/main/java/nl/topicus/onderwijs/uwlr/shared/webservice/interceptors/FaultInterceptor.java | 431 | // Kijk of in de message een Exception verpakt zit | line_comment | nl | package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors;
import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2;
import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.phase.Phase;
/**
* Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt
* en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de
* {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de
* UWLR afspraak.
*/
public class FaultInterceptor extends AbstractSoapInterceptor {
public FaultInterceptor() {
super(Phase.PRE_LOGICAL);
}
@Override
public void handleMessage(final SoapMessage message) {
// Kijk of<SUF>
Object exception = message.getContent(Exception.class);
// Als er een exception is die niet van het type SoapFault is, dan moet deze
// vertaald worden naar een SoapFault.
if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault)))
message.setContent(
Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause()));
}
}
|
175578_0 | package com.ambow.lyu.common.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* @author woondeewyy
* @date 2019/5/28
*/
public class HanyuPinyinUtils {
/**
* 将文字转为汉语拼音
*
* @param chineseLanguage 要转成拼音的中文
*/
public static String toHanyuPinyin(String chineseLanguage) {
StringBuilder result = new StringBuilder();
char[] clChars = chineseLanguage.trim().toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 输出拼音全部小写
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 不带声调
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
for (char clChar : clChars) {
//如果字符是中文,则将中文转为汉语拼音
if (String.valueOf(clChar).matches("[\u4e00-\u9fa5]+")) {
try {
result.append(PinyinHelper.toHanyuPinyinStringArray(clChar, defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
}
}
return result.toString();
}
}
| tameng0821/teacher_evaluation | te-common/src/main/java/com/ambow/lyu/common/utils/HanyuPinyinUtils.java | 555 | /**
* @author woondeewyy
* @date 2019/5/28
*/ | block_comment | nl | package com.ambow.lyu.common.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* @author woondeewyy
<SUF>*/
public class HanyuPinyinUtils {
/**
* 将文字转为汉语拼音
*
* @param chineseLanguage 要转成拼音的中文
*/
public static String toHanyuPinyin(String chineseLanguage) {
StringBuilder result = new StringBuilder();
char[] clChars = chineseLanguage.trim().toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 输出拼音全部小写
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 不带声调
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
for (char clChar : clChars) {
//如果字符是中文,则将中文转为汉语拼音
if (String.valueOf(clChar).matches("[\u4e00-\u9fa5]+")) {
try {
result.append(PinyinHelper.toHanyuPinyinStringArray(clChar, defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
}
}
return result.toString();
}
}
|
71979_13 | package kapsalon.nl.services;
import jakarta.persistence.EntityNotFoundException;
import kapsalon.nl.exceptions.RecordNotFoundException;
import kapsalon.nl.models.dto.BarberDTO;
import kapsalon.nl.models.dto.DienstDTO;
import kapsalon.nl.models.entity.Barber;
import kapsalon.nl.models.entity.Dienst;
import kapsalon.nl.models.entity.Kapsalon;
import kapsalon.nl.repo.BarberRepository;
import kapsalon.nl.repo.DienstRepository;
import kapsalon.nl.repo.KapsalonRepository;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class BarberServiceImpl implements BarberService {
private final BarberRepository barberRepository;
private final KapsalonRepository kapsalonRepository;
private final DienstRepository dienstRepository;
public BarberServiceImpl(BarberRepository kapperRepository, KapsalonRepository kapsalonRepository, DienstRepository dienstRepository){
this.barberRepository = kapperRepository;
this.kapsalonRepository =kapsalonRepository;
this.dienstRepository = dienstRepository;
}
@Override
public List<BarberDTO> findAvailableBarbers() {
List<Barber> availableBarbers = barberRepository.findByAvailableTrue();
return availableBarbers.stream().map(this::fromEntityToDto).collect(Collectors.toList());
}
@Override
public List<BarberDTO> getAllBarbers() {
List<Barber> entityList = barberRepository.findAll();
List<BarberDTO> dtoList = new ArrayList<>();
for (Barber entity : entityList) {
dtoList.add(fromEntityToDto(entity));
}
return dtoList;
}
@Override
public BarberDTO getBarberById(Long id) {
Barber entity = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
return fromEntityToDto(entity);
}
@Override
public BarberDTO createBarber(BarberDTO dto) {
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de lijst leeg is
if (ownerKapsalons.isEmpty()) {
throw new AccessDeniedException("Only owners with kapsalons can add barbers. If you don't have a kapsalon yet, please create one.");
}
// Controleer of de kapsalon in het DTO overeenkomt met een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(dto.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only add barbers to your own kapsalon. check what your kapsalon ID is.");
}
// // Controleer of alle diensten in het DTO bestaan
// for (Dienst dienst : dto.getDiensten()) {
// dienstRepository.findById(dienst.getId())
// .orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dienst.getId()));
// }
Barber entity = barberRepository.save(fromDtoToEntity(dto));
Kapsalon kapsalon = kapsalonRepository.findById(dto.getKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getKapsalon().getId()));
entity.setKapsalon(kapsalon);
return fromEntityToDto(entity);
}
@Override
public BarberDTO updateBarber(Long id, BarberDTO dto) {
// Haal de originele barber op
Barber entity = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de barber behoort tot een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(entity.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only update barbers in your own kapsalons. check the Barber ID");
}
// Update de eigenschappen van de barber
entity.setName(dto.getName());
entity.setAvailable(dto.isAvailable());
entity.setLicense(dto.getLicense());
// Controleer of de kapsalon in het DTO overeenkomt met een van de kapsalons van de eigenaar
Optional<Kapsalon> optionalKapsalon = ownerKapsalons.stream()
.filter(kapsalon -> kapsalon.getId().equals(dto.getKapsalon().getId()))
.findFirst();
// Als de kapsalon niet wordt gevonden, gooi een AccessDeniedException
if (optionalKapsalon.isEmpty()) {
throw new AccessDeniedException("You can only update barbers in your own kapsalons. check the Kapsalon ID");
}
// Stel de nieuwe kapsalon in
entity.setKapsalon(optionalKapsalon.get());
entity.setDiensten(dto.getDiensten());
// Sla de bijgewerkte barber op
Barber updatedEntity = barberRepository.save(entity);
// Geef het DTO-object terug
return fromEntityToDto(updatedEntity);
}
@Override
public void deleteBarber(Long id) {
// Haal de originele barber op
Barber barber = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de barber behoort tot een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(barber.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only delete barbers in your own kapsalons. check the Barber ID");
}
// Verwijder de barber
barberRepository.delete(barber);
}
private String getLoggedInUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
}
public BarberDTO fromEntityToDto(Barber entity){
BarberDTO dto = new BarberDTO();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setAvailable(entity.isAvailable());
dto.setLicense(entity.getLicense());
dto.setKapsalon(entity.getKapsalon());
dto.setDiensten(entity.getDiensten());
return dto;
}
public Barber fromDtoToEntity(BarberDTO dto) {
Barber entity = new Barber();
entity.setId(dto.getId());
entity.setName(dto.getName());
entity.setAvailable(dto.isAvailable());
entity.setLicense(dto.getLicense());
entity.setKapsalon(dto.getKapsalon());
entity.setDiensten(dto.getDiensten());
return entity;
}
}
| tamer4k/kapsalon | src/main/java/kapsalon/nl/services/BarberServiceImpl.java | 2,280 | // Als de kapsalon niet wordt gevonden, gooi een AccessDeniedException | line_comment | nl | package kapsalon.nl.services;
import jakarta.persistence.EntityNotFoundException;
import kapsalon.nl.exceptions.RecordNotFoundException;
import kapsalon.nl.models.dto.BarberDTO;
import kapsalon.nl.models.dto.DienstDTO;
import kapsalon.nl.models.entity.Barber;
import kapsalon.nl.models.entity.Dienst;
import kapsalon.nl.models.entity.Kapsalon;
import kapsalon.nl.repo.BarberRepository;
import kapsalon.nl.repo.DienstRepository;
import kapsalon.nl.repo.KapsalonRepository;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class BarberServiceImpl implements BarberService {
private final BarberRepository barberRepository;
private final KapsalonRepository kapsalonRepository;
private final DienstRepository dienstRepository;
public BarberServiceImpl(BarberRepository kapperRepository, KapsalonRepository kapsalonRepository, DienstRepository dienstRepository){
this.barberRepository = kapperRepository;
this.kapsalonRepository =kapsalonRepository;
this.dienstRepository = dienstRepository;
}
@Override
public List<BarberDTO> findAvailableBarbers() {
List<Barber> availableBarbers = barberRepository.findByAvailableTrue();
return availableBarbers.stream().map(this::fromEntityToDto).collect(Collectors.toList());
}
@Override
public List<BarberDTO> getAllBarbers() {
List<Barber> entityList = barberRepository.findAll();
List<BarberDTO> dtoList = new ArrayList<>();
for (Barber entity : entityList) {
dtoList.add(fromEntityToDto(entity));
}
return dtoList;
}
@Override
public BarberDTO getBarberById(Long id) {
Barber entity = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
return fromEntityToDto(entity);
}
@Override
public BarberDTO createBarber(BarberDTO dto) {
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de lijst leeg is
if (ownerKapsalons.isEmpty()) {
throw new AccessDeniedException("Only owners with kapsalons can add barbers. If you don't have a kapsalon yet, please create one.");
}
// Controleer of de kapsalon in het DTO overeenkomt met een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(dto.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only add barbers to your own kapsalon. check what your kapsalon ID is.");
}
// // Controleer of alle diensten in het DTO bestaan
// for (Dienst dienst : dto.getDiensten()) {
// dienstRepository.findById(dienst.getId())
// .orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dienst.getId()));
// }
Barber entity = barberRepository.save(fromDtoToEntity(dto));
Kapsalon kapsalon = kapsalonRepository.findById(dto.getKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getKapsalon().getId()));
entity.setKapsalon(kapsalon);
return fromEntityToDto(entity);
}
@Override
public BarberDTO updateBarber(Long id, BarberDTO dto) {
// Haal de originele barber op
Barber entity = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de barber behoort tot een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(entity.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only update barbers in your own kapsalons. check the Barber ID");
}
// Update de eigenschappen van de barber
entity.setName(dto.getName());
entity.setAvailable(dto.isAvailable());
entity.setLicense(dto.getLicense());
// Controleer of de kapsalon in het DTO overeenkomt met een van de kapsalons van de eigenaar
Optional<Kapsalon> optionalKapsalon = ownerKapsalons.stream()
.filter(kapsalon -> kapsalon.getId().equals(dto.getKapsalon().getId()))
.findFirst();
// Als de<SUF>
if (optionalKapsalon.isEmpty()) {
throw new AccessDeniedException("You can only update barbers in your own kapsalons. check the Kapsalon ID");
}
// Stel de nieuwe kapsalon in
entity.setKapsalon(optionalKapsalon.get());
entity.setDiensten(dto.getDiensten());
// Sla de bijgewerkte barber op
Barber updatedEntity = barberRepository.save(entity);
// Geef het DTO-object terug
return fromEntityToDto(updatedEntity);
}
@Override
public void deleteBarber(Long id) {
// Haal de originele barber op
Barber barber = barberRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("No Barber found with ID: " + id));
// Haal de ingelogde gebruikersnaam op
String loggedInUsername = getLoggedInUsername();
// Zoek alle kapsalons van de ingelogde gebruiker op
List<Kapsalon> ownerKapsalons = kapsalonRepository.findAllByOwner(loggedInUsername);
// Controleer of de barber behoort tot een van de kapsalons van de eigenaar
if (ownerKapsalons.stream().noneMatch(kapsalon -> kapsalon.getId().equals(barber.getKapsalon().getId()))) {
throw new AccessDeniedException("You can only delete barbers in your own kapsalons. check the Barber ID");
}
// Verwijder de barber
barberRepository.delete(barber);
}
private String getLoggedInUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
}
public BarberDTO fromEntityToDto(Barber entity){
BarberDTO dto = new BarberDTO();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setAvailable(entity.isAvailable());
dto.setLicense(entity.getLicense());
dto.setKapsalon(entity.getKapsalon());
dto.setDiensten(entity.getDiensten());
return dto;
}
public Barber fromDtoToEntity(BarberDTO dto) {
Barber entity = new Barber();
entity.setId(dto.getId());
entity.setName(dto.getName());
entity.setAvailable(dto.isAvailable());
entity.setLicense(dto.getLicense());
entity.setKapsalon(dto.getKapsalon());
entity.setDiensten(dto.getDiensten());
return entity;
}
}
|
162214_77 | /*
* Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.awt;
import java.awt.MultipleGradientPaint.CycleMethod;
import java.awt.MultipleGradientPaint.ColorSpaceType;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Arrays;
/**
* This is the superclass for all PaintContexts which use a multiple color
* gradient to fill in their raster. It provides the actual color
* interpolation functionality. Subclasses only have to deal with using
* the gradient to fill pixels in a raster.
*
* @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
*/
abstract class MultipleGradientPaintContext implements PaintContext {
/**
* The PaintContext's ColorModel. This is ARGB if colors are not all
* opaque, otherwise it is RGB.
*/
protected ColorModel model;
/** Color model used if gradient colors are all opaque. */
private static ColorModel xrgbmodel =
new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
/** The cached ColorModel. */
protected static ColorModel cachedModel;
/** The cached raster, which is reusable among instances. */
protected static WeakReference<Raster> cached;
/** Raster is reused whenever possible. */
protected Raster saved;
/** The method to use when painting out of the gradient bounds. */
protected CycleMethod cycleMethod;
/** The ColorSpace in which to perform the interpolation */
protected ColorSpaceType colorSpace;
/** Elements of the inverse transform matrix. */
protected float a00, a01, a10, a11, a02, a12;
/**
* This boolean specifies wether we are in simple lookup mode, where an
* input value between 0 and 1 may be used to directly index into a single
* array of gradient colors. If this boolean value is false, then we have
* to use a 2-step process where we have to determine which gradient array
* we fall into, then determine the index into that array.
*/
protected boolean isSimpleLookup;
/**
* Size of gradients array for scaling the 0-1 index when looking up
* colors the fast way.
*/
protected int fastGradientArraySize;
/**
* Array which contains the interpolated color values for each interval,
* used by calculateSingleArrayGradient(). It is protected for possible
* direct access by subclasses.
*/
protected int[] gradient;
/**
* Array of gradient arrays, one array for each interval. Used by
* calculateMultipleArrayGradient().
*/
private int[][] gradients;
/** Normalized intervals array. */
private float[] normalizedIntervals;
/** Fractions array. */
private float[] fractions;
/** Used to determine if gradient colors are all opaque. */
private int transparencyTest;
/** Color space conversion lookup tables. */
private static final int SRGBtoLinearRGB[] = new int[256];
private static final int LinearRGBtoSRGB[] = new int[256];
static {
// build the tables
for (int k = 0; k < 256; k++) {
SRGBtoLinearRGB[k] = convertSRGBtoLinearRGB(k);
LinearRGBtoSRGB[k] = convertLinearRGBtoSRGB(k);
}
}
/**
* Constant number of max colors between any 2 arbitrary colors.
* Used for creating and indexing gradients arrays.
*/
protected static final int GRADIENT_SIZE = 256;
protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE -1;
/**
* Maximum length of the fast single-array. If the estimated array size
* is greater than this, switch over to the slow lookup method.
* No particular reason for choosing this number, but it seems to provide
* satisfactory performance for the common case (fast lookup).
*/
private static final int MAX_GRADIENT_ARRAY_SIZE = 5000;
/**
* Constructor for MultipleGradientPaintContext superclass.
*/
protected MultipleGradientPaintContext(MultipleGradientPaint mgp,
ColorModel cm,
Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform t,
RenderingHints hints,
float[] fractions,
Color[] colors,
CycleMethod cycleMethod,
ColorSpaceType colorSpace)
{
if (deviceBounds == null) {
throw new NullPointerException("Device bounds cannot be null");
}
if (userBounds == null) {
throw new NullPointerException("User bounds cannot be null");
}
if (t == null) {
throw new NullPointerException("Transform cannot be null");
}
if (hints == null) {
throw new NullPointerException("RenderingHints cannot be null");
}
// The inverse transform is needed to go from device to user space.
// Get all the components of the inverse transform matrix.
AffineTransform tInv;
try {
// the following assumes that the caller has copied the incoming
// transform and is not concerned about it being modified
t.invert();
tInv = t;
} catch (NoninvertibleTransformException e) {
// just use identity transform in this case; better to show
// (incorrect) results than to throw an exception and/or no-op
tInv = new AffineTransform();
}
double m[] = new double[6];
tInv.getMatrix(m);
a00 = (float)m[0];
a10 = (float)m[1];
a01 = (float)m[2];
a11 = (float)m[3];
a02 = (float)m[4];
a12 = (float)m[5];
// copy some flags
this.cycleMethod = cycleMethod;
this.colorSpace = colorSpace;
// we can avoid copying this array since we do not modify its values
this.fractions = fractions;
// note that only one of these values can ever be non-null (we either
// store the fast gradient array or the slow one, but never both
// at the same time)
int[] gradient =
(mgp.gradient != null) ? mgp.gradient.get() : null;
int[][] gradients =
(mgp.gradients != null) ? mgp.gradients.get() : null;
if (gradient == null && gradients == null) {
// we need to (re)create the appropriate values
calculateLookupData(colors);
// now cache the calculated values in the
// MultipleGradientPaint instance for future use
mgp.model = this.model;
mgp.normalizedIntervals = this.normalizedIntervals;
mgp.isSimpleLookup = this.isSimpleLookup;
if (isSimpleLookup) {
// only cache the fast array
mgp.fastGradientArraySize = this.fastGradientArraySize;
mgp.gradient = new SoftReference<int[]>(this.gradient);
} else {
// only cache the slow array
mgp.gradients = new SoftReference<int[][]>(this.gradients);
}
} else {
// use the values cached in the MultipleGradientPaint instance
this.model = mgp.model;
this.normalizedIntervals = mgp.normalizedIntervals;
this.isSimpleLookup = mgp.isSimpleLookup;
this.gradient = gradient;
this.fastGradientArraySize = mgp.fastGradientArraySize;
this.gradients = gradients;
}
}
/**
* This function is the meat of this class. It calculates an array of
* gradient colors based on an array of fractions and color values at
* those fractions.
*/
private void calculateLookupData(Color[] colors) {
Color[] normalizedColors;
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
// create a new colors array
normalizedColors = new Color[colors.length];
// convert the colors using the lookup table
for (int i = 0; i < colors.length; i++) {
int argb = colors[i].getRGB();
int a = argb >>> 24;
int r = SRGBtoLinearRGB[(argb >> 16) & 0xff];
int g = SRGBtoLinearRGB[(argb >> 8) & 0xff];
int b = SRGBtoLinearRGB[(argb ) & 0xff];
normalizedColors[i] = new Color(r, g, b, a);
}
} else {
// we can just use this array by reference since we do not
// modify its values in the case of SRGB
normalizedColors = colors;
}
// this will store the intervals (distances) between gradient stops
normalizedIntervals = new float[fractions.length-1];
// convert from fractions into intervals
for (int i = 0; i < normalizedIntervals.length; i++) {
// interval distance is equal to the difference in positions
normalizedIntervals[i] = this.fractions[i+1] - this.fractions[i];
}
// initialize to be fully opaque for ANDing with colors
transparencyTest = 0xff000000;
// array of interpolation arrays
gradients = new int[normalizedIntervals.length][];
// find smallest interval
float Imin = 1;
for (int i = 0; i < normalizedIntervals.length; i++) {
Imin = (Imin > normalizedIntervals[i]) ?
normalizedIntervals[i] : Imin;
}
// Estimate the size of the entire gradients array.
// This is to prevent a tiny interval from causing the size of array
// to explode. If the estimated size is too large, break to using
// separate arrays for each interval, and using an indexing scheme at
// look-up time.
int estimatedSize = 0;
for (int i = 0; i < normalizedIntervals.length; i++) {
estimatedSize += (normalizedIntervals[i]/Imin) * GRADIENT_SIZE;
}
if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) {
// slow method
calculateMultipleArrayGradient(normalizedColors);
} else {
// fast method
calculateSingleArrayGradient(normalizedColors, Imin);
}
// use the most "economical" model
if ((transparencyTest >>> 24) == 0xff) {
model = xrgbmodel;
} else {
model = ColorModel.getRGBdefault();
}
}
/**
* FAST LOOKUP METHOD
*
* This method calculates the gradient color values and places them in a
* single int array, gradient[]. It does this by allocating space for
* each interval based on its size relative to the smallest interval in
* the array. The smallest interval is allocated 255 interpolated values
* (the maximum number of unique in-between colors in a 24 bit color
* system), and all other intervals are allocated
* size = (255 * the ratio of their size to the smallest interval).
*
* This scheme expedites a speedy retrieval because the colors are
* distributed along the array according to their user-specified
* distribution. All that is needed is a relative index from 0 to 1.
*
* The only problem with this method is that the possibility exists for
* the array size to balloon in the case where there is a
* disproportionately small gradient interval. In this case the other
* intervals will be allocated huge space, but much of that data is
* redundant. We thus need to use the space conserving scheme below.
*
* @param Imin the size of the smallest interval
*/
private void calculateSingleArrayGradient(Color[] colors, float Imin) {
// set the flag so we know later it is a simple (fast) lookup
isSimpleLookup = true;
// 2 colors to interpolate
int rgb1, rgb2;
//the eventual size of the single array
int gradientsTot = 1;
// for every interval (transition between 2 colors)
for (int i = 0; i < gradients.length; i++) {
// create an array whose size is based on the ratio to the
// smallest interval
int nGradients = (int)((normalizedIntervals[i]/Imin)*255f);
gradientsTot += nGradients;
gradients[i] = new int[nGradients];
// the 2 colors (keyframes) to interpolate between
rgb1 = colors[i].getRGB();
rgb2 = colors[i+1].getRGB();
// fill this array with the colors in between rgb1 and rgb2
interpolate(rgb1, rgb2, gradients[i]);
// if the colors are opaque, transparency should still
// be 0xff000000
transparencyTest &= rgb1;
transparencyTest &= rgb2;
}
// put all gradients in a single array
gradient = new int[gradientsTot];
int curOffset = 0;
for (int i = 0; i < gradients.length; i++){
System.arraycopy(gradients[i], 0, gradient,
curOffset, gradients[i].length);
curOffset += gradients[i].length;
}
gradient[gradient.length-1] = colors[colors.length-1].getRGB();
// if interpolation occurred in Linear RGB space, convert the
// gradients back to sRGB using the lookup table
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
for (int i = 0; i < gradient.length; i++) {
gradient[i] = convertEntireColorLinearRGBtoSRGB(gradient[i]);
}
}
fastGradientArraySize = gradient.length - 1;
}
/**
* SLOW LOOKUP METHOD
*
* This method calculates the gradient color values for each interval and
* places each into its own 255 size array. The arrays are stored in
* gradients[][]. (255 is used because this is the maximum number of
* unique colors between 2 arbitrary colors in a 24 bit color system.)
*
* This method uses the minimum amount of space (only 255 * number of
* intervals), but it aggravates the lookup procedure, because now we
* have to find out which interval to select, then calculate the index
* within that interval. This causes a significant performance hit,
* because it requires this calculation be done for every point in
* the rendering loop.
*
* For those of you who are interested, this is a classic example of the
* time-space tradeoff.
*/
private void calculateMultipleArrayGradient(Color[] colors) {
// set the flag so we know later it is a non-simple lookup
isSimpleLookup = false;
// 2 colors to interpolate
int rgb1, rgb2;
// for every interval (transition between 2 colors)
for (int i = 0; i < gradients.length; i++){
// create an array of the maximum theoretical size for
// each interval
gradients[i] = new int[GRADIENT_SIZE];
// get the the 2 colors
rgb1 = colors[i].getRGB();
rgb2 = colors[i+1].getRGB();
// fill this array with the colors in between rgb1 and rgb2
interpolate(rgb1, rgb2, gradients[i]);
// if the colors are opaque, transparency should still
// be 0xff000000
transparencyTest &= rgb1;
transparencyTest &= rgb2;
}
// if interpolation occurred in Linear RGB space, convert the
// gradients back to SRGB using the lookup table
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
for (int j = 0; j < gradients.length; j++) {
for (int i = 0; i < gradients[j].length; i++) {
gradients[j][i] =
convertEntireColorLinearRGBtoSRGB(gradients[j][i]);
}
}
}
}
/**
* Yet another helper function. This one linearly interpolates between
* 2 colors, filling up the output array.
*
* @param rgb1 the start color
* @param rgb2 the end color
* @param output the output array of colors; must not be null
*/
private void interpolate(int rgb1, int rgb2, int[] output) {
// color components
int a1, r1, g1, b1, da, dr, dg, db;
// step between interpolated values
float stepSize = 1.0f / output.length;
// extract color components from packed integer
a1 = (rgb1 >> 24) & 0xff;
r1 = (rgb1 >> 16) & 0xff;
g1 = (rgb1 >> 8) & 0xff;
b1 = (rgb1 ) & 0xff;
// calculate the total change in alpha, red, green, blue
da = ((rgb2 >> 24) & 0xff) - a1;
dr = ((rgb2 >> 16) & 0xff) - r1;
dg = ((rgb2 >> 8) & 0xff) - g1;
db = ((rgb2 ) & 0xff) - b1;
// for each step in the interval calculate the in-between color by
// multiplying the normalized current position by the total color
// change (0.5 is added to prevent truncation round-off error)
for (int i = 0; i < output.length; i++) {
output[i] =
(((int) ((a1 + i * da * stepSize) + 0.5) << 24)) |
(((int) ((r1 + i * dr * stepSize) + 0.5) << 16)) |
(((int) ((g1 + i * dg * stepSize) + 0.5) << 8)) |
(((int) ((b1 + i * db * stepSize) + 0.5) ));
}
}
/**
* Yet another helper function. This one extracts the color components
* of an integer RGB triple, converts them from LinearRGB to SRGB, then
* recompacts them into an int.
*/
private int convertEntireColorLinearRGBtoSRGB(int rgb) {
// color components
int a1, r1, g1, b1;
// extract red, green, blue components
a1 = (rgb >> 24) & 0xff;
r1 = (rgb >> 16) & 0xff;
g1 = (rgb >> 8) & 0xff;
b1 = (rgb ) & 0xff;
// use the lookup table
r1 = LinearRGBtoSRGB[r1];
g1 = LinearRGBtoSRGB[g1];
b1 = LinearRGBtoSRGB[b1];
// re-compact the components
return ((a1 << 24) |
(r1 << 16) |
(g1 << 8) |
(b1 ));
}
/**
* Helper function to index into the gradients array. This is necessary
* because each interval has an array of colors with uniform size 255.
* However, the color intervals are not necessarily of uniform length, so
* a conversion is required.
*
* @param position the unmanipulated position, which will be mapped
* into the range 0 to 1
* @returns integer color to display
*/
protected final int indexIntoGradientsArrays(float position) {
// first, manipulate position value depending on the cycle method
if (cycleMethod == CycleMethod.NO_CYCLE) {
if (position > 1) {
// upper bound is 1
position = 1;
} else if (position < 0) {
// lower bound is 0
position = 0;
}
} else if (cycleMethod == CycleMethod.REPEAT) {
// get the fractional part
// (modulo behavior discards integer component)
position = position - (int)position;
//position should now be between -1 and 1
if (position < 0) {
// force it to be in the range 0-1
position = position + 1;
}
} else { // cycleMethod == CycleMethod.REFLECT
if (position < 0) {
// take absolute value
position = -position;
}
// get the integer part
int part = (int)position;
// get the fractional part
position = position - part;
if ((part & 1) == 1) {
// integer part is odd, get reflected color instead
position = 1 - position;
}
}
// now, get the color based on this 0-1 position...
if (isSimpleLookup) {
// easy to compute: just scale index by array size
return gradient[(int)(position * fastGradientArraySize)];
} else {
// more complicated computation, to save space
// for all the gradient interval arrays
for (int i = 0; i < gradients.length; i++) {
if (position < fractions[i+1]) {
// this is the array we want
float delta = position - fractions[i];
// this is the interval we want
int index = (int)((delta / normalizedIntervals[i])
* (GRADIENT_SIZE_INDEX));
return gradients[i][index];
}
}
}
return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX];
}
/**
* Helper function to convert a color component in sRGB space to linear
* RGB space. Used to build a static lookup table.
*/
private static int convertSRGBtoLinearRGB(int color) {
float input, output;
input = color / 255.0f;
if (input <= 0.04045f) {
output = input / 12.92f;
} else {
output = (float)Math.pow((input + 0.055) / 1.055, 2.4);
}
return Math.round(output * 255.0f);
}
/**
* Helper function to convert a color component in linear RGB space to
* SRGB space. Used to build a static lookup table.
*/
private static int convertLinearRGBtoSRGB(int color) {
float input, output;
input = color/255.0f;
if (input <= 0.0031308) {
output = input * 12.92f;
} else {
output = (1.055f *
((float) Math.pow(input, (1.0 / 2.4)))) - 0.055f;
}
return Math.round(output * 255.0f);
}
/**
* {@inheritDoc}
*/
public final Raster getRaster(int x, int y, int w, int h) {
// If working raster is big enough, reuse it. Otherwise,
// build a large enough new one.
Raster raster = saved;
if (raster == null ||
raster.getWidth() < w || raster.getHeight() < h)
{
raster = getCachedRaster(model, w, h);
saved = raster;
}
// Access raster internal int array. Because we use a DirectColorModel,
// we know the DataBuffer is of type DataBufferInt and the SampleModel
// is SinglePixelPackedSampleModel.
// Adjust for initial offset in DataBuffer and also for the scanline
// stride.
// These calls make the DataBuffer non-acceleratable, but the
// Raster is never Stable long enough to accelerate anyway...
DataBufferInt rasterDB = (DataBufferInt)raster.getDataBuffer();
int[] pixels = rasterDB.getData(0);
int off = rasterDB.getOffset();
int scanlineStride = ((SinglePixelPackedSampleModel)
raster.getSampleModel()).getScanlineStride();
int adjust = scanlineStride - w;
fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass
return raster;
}
protected abstract void fillRaster(int pixels[], int off, int adjust,
int x, int y, int w, int h);
/**
* Took this cacheRaster code from GradientPaint. It appears to recycle
* rasters for use by any other instance, as long as they are sufficiently
* large.
*/
private static synchronized Raster getCachedRaster(ColorModel cm,
int w, int h)
{
if (cm == cachedModel) {
if (cached != null) {
Raster ras = (Raster) cached.get();
if (ras != null &&
ras.getWidth() >= w &&
ras.getHeight() >= h)
{
cached = null;
return ras;
}
}
}
return cm.createCompatibleWritableRaster(w, h);
}
/**
* Took this cacheRaster code from GradientPaint. It appears to recycle
* rasters for use by any other instance, as long as they are sufficiently
* large.
*/
private static synchronized void putCachedRaster(ColorModel cm,
Raster ras)
{
if (cached != null) {
Raster cras = (Raster) cached.get();
if (cras != null) {
int cw = cras.getWidth();
int ch = cras.getHeight();
int iw = ras.getWidth();
int ih = ras.getHeight();
if (cw >= iw && ch >= ih) {
return;
}
if (cw * ch >= iw * ih) {
return;
}
}
}
cachedModel = cm;
cached = new WeakReference<Raster>(ras);
}
/**
* {@inheritDoc}
*/
public final void dispose() {
if (saved != null) {
putCachedRaster(model, saved);
saved = null;
}
}
/**
* {@inheritDoc}
*/
public final ColorModel getColorModel() {
return model;
}
}
| taotaoideas/JDK-1 | JDK1.7-Java SE Development Kit 7u80/src/java/awt/MultipleGradientPaintContext.java | 7,208 | // step between interpolated values | line_comment | nl | /*
* Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.awt;
import java.awt.MultipleGradientPaint.CycleMethod;
import java.awt.MultipleGradientPaint.ColorSpaceType;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Arrays;
/**
* This is the superclass for all PaintContexts which use a multiple color
* gradient to fill in their raster. It provides the actual color
* interpolation functionality. Subclasses only have to deal with using
* the gradient to fill pixels in a raster.
*
* @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
*/
abstract class MultipleGradientPaintContext implements PaintContext {
/**
* The PaintContext's ColorModel. This is ARGB if colors are not all
* opaque, otherwise it is RGB.
*/
protected ColorModel model;
/** Color model used if gradient colors are all opaque. */
private static ColorModel xrgbmodel =
new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
/** The cached ColorModel. */
protected static ColorModel cachedModel;
/** The cached raster, which is reusable among instances. */
protected static WeakReference<Raster> cached;
/** Raster is reused whenever possible. */
protected Raster saved;
/** The method to use when painting out of the gradient bounds. */
protected CycleMethod cycleMethod;
/** The ColorSpace in which to perform the interpolation */
protected ColorSpaceType colorSpace;
/** Elements of the inverse transform matrix. */
protected float a00, a01, a10, a11, a02, a12;
/**
* This boolean specifies wether we are in simple lookup mode, where an
* input value between 0 and 1 may be used to directly index into a single
* array of gradient colors. If this boolean value is false, then we have
* to use a 2-step process where we have to determine which gradient array
* we fall into, then determine the index into that array.
*/
protected boolean isSimpleLookup;
/**
* Size of gradients array for scaling the 0-1 index when looking up
* colors the fast way.
*/
protected int fastGradientArraySize;
/**
* Array which contains the interpolated color values for each interval,
* used by calculateSingleArrayGradient(). It is protected for possible
* direct access by subclasses.
*/
protected int[] gradient;
/**
* Array of gradient arrays, one array for each interval. Used by
* calculateMultipleArrayGradient().
*/
private int[][] gradients;
/** Normalized intervals array. */
private float[] normalizedIntervals;
/** Fractions array. */
private float[] fractions;
/** Used to determine if gradient colors are all opaque. */
private int transparencyTest;
/** Color space conversion lookup tables. */
private static final int SRGBtoLinearRGB[] = new int[256];
private static final int LinearRGBtoSRGB[] = new int[256];
static {
// build the tables
for (int k = 0; k < 256; k++) {
SRGBtoLinearRGB[k] = convertSRGBtoLinearRGB(k);
LinearRGBtoSRGB[k] = convertLinearRGBtoSRGB(k);
}
}
/**
* Constant number of max colors between any 2 arbitrary colors.
* Used for creating and indexing gradients arrays.
*/
protected static final int GRADIENT_SIZE = 256;
protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE -1;
/**
* Maximum length of the fast single-array. If the estimated array size
* is greater than this, switch over to the slow lookup method.
* No particular reason for choosing this number, but it seems to provide
* satisfactory performance for the common case (fast lookup).
*/
private static final int MAX_GRADIENT_ARRAY_SIZE = 5000;
/**
* Constructor for MultipleGradientPaintContext superclass.
*/
protected MultipleGradientPaintContext(MultipleGradientPaint mgp,
ColorModel cm,
Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform t,
RenderingHints hints,
float[] fractions,
Color[] colors,
CycleMethod cycleMethod,
ColorSpaceType colorSpace)
{
if (deviceBounds == null) {
throw new NullPointerException("Device bounds cannot be null");
}
if (userBounds == null) {
throw new NullPointerException("User bounds cannot be null");
}
if (t == null) {
throw new NullPointerException("Transform cannot be null");
}
if (hints == null) {
throw new NullPointerException("RenderingHints cannot be null");
}
// The inverse transform is needed to go from device to user space.
// Get all the components of the inverse transform matrix.
AffineTransform tInv;
try {
// the following assumes that the caller has copied the incoming
// transform and is not concerned about it being modified
t.invert();
tInv = t;
} catch (NoninvertibleTransformException e) {
// just use identity transform in this case; better to show
// (incorrect) results than to throw an exception and/or no-op
tInv = new AffineTransform();
}
double m[] = new double[6];
tInv.getMatrix(m);
a00 = (float)m[0];
a10 = (float)m[1];
a01 = (float)m[2];
a11 = (float)m[3];
a02 = (float)m[4];
a12 = (float)m[5];
// copy some flags
this.cycleMethod = cycleMethod;
this.colorSpace = colorSpace;
// we can avoid copying this array since we do not modify its values
this.fractions = fractions;
// note that only one of these values can ever be non-null (we either
// store the fast gradient array or the slow one, but never both
// at the same time)
int[] gradient =
(mgp.gradient != null) ? mgp.gradient.get() : null;
int[][] gradients =
(mgp.gradients != null) ? mgp.gradients.get() : null;
if (gradient == null && gradients == null) {
// we need to (re)create the appropriate values
calculateLookupData(colors);
// now cache the calculated values in the
// MultipleGradientPaint instance for future use
mgp.model = this.model;
mgp.normalizedIntervals = this.normalizedIntervals;
mgp.isSimpleLookup = this.isSimpleLookup;
if (isSimpleLookup) {
// only cache the fast array
mgp.fastGradientArraySize = this.fastGradientArraySize;
mgp.gradient = new SoftReference<int[]>(this.gradient);
} else {
// only cache the slow array
mgp.gradients = new SoftReference<int[][]>(this.gradients);
}
} else {
// use the values cached in the MultipleGradientPaint instance
this.model = mgp.model;
this.normalizedIntervals = mgp.normalizedIntervals;
this.isSimpleLookup = mgp.isSimpleLookup;
this.gradient = gradient;
this.fastGradientArraySize = mgp.fastGradientArraySize;
this.gradients = gradients;
}
}
/**
* This function is the meat of this class. It calculates an array of
* gradient colors based on an array of fractions and color values at
* those fractions.
*/
private void calculateLookupData(Color[] colors) {
Color[] normalizedColors;
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
// create a new colors array
normalizedColors = new Color[colors.length];
// convert the colors using the lookup table
for (int i = 0; i < colors.length; i++) {
int argb = colors[i].getRGB();
int a = argb >>> 24;
int r = SRGBtoLinearRGB[(argb >> 16) & 0xff];
int g = SRGBtoLinearRGB[(argb >> 8) & 0xff];
int b = SRGBtoLinearRGB[(argb ) & 0xff];
normalizedColors[i] = new Color(r, g, b, a);
}
} else {
// we can just use this array by reference since we do not
// modify its values in the case of SRGB
normalizedColors = colors;
}
// this will store the intervals (distances) between gradient stops
normalizedIntervals = new float[fractions.length-1];
// convert from fractions into intervals
for (int i = 0; i < normalizedIntervals.length; i++) {
// interval distance is equal to the difference in positions
normalizedIntervals[i] = this.fractions[i+1] - this.fractions[i];
}
// initialize to be fully opaque for ANDing with colors
transparencyTest = 0xff000000;
// array of interpolation arrays
gradients = new int[normalizedIntervals.length][];
// find smallest interval
float Imin = 1;
for (int i = 0; i < normalizedIntervals.length; i++) {
Imin = (Imin > normalizedIntervals[i]) ?
normalizedIntervals[i] : Imin;
}
// Estimate the size of the entire gradients array.
// This is to prevent a tiny interval from causing the size of array
// to explode. If the estimated size is too large, break to using
// separate arrays for each interval, and using an indexing scheme at
// look-up time.
int estimatedSize = 0;
for (int i = 0; i < normalizedIntervals.length; i++) {
estimatedSize += (normalizedIntervals[i]/Imin) * GRADIENT_SIZE;
}
if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) {
// slow method
calculateMultipleArrayGradient(normalizedColors);
} else {
// fast method
calculateSingleArrayGradient(normalizedColors, Imin);
}
// use the most "economical" model
if ((transparencyTest >>> 24) == 0xff) {
model = xrgbmodel;
} else {
model = ColorModel.getRGBdefault();
}
}
/**
* FAST LOOKUP METHOD
*
* This method calculates the gradient color values and places them in a
* single int array, gradient[]. It does this by allocating space for
* each interval based on its size relative to the smallest interval in
* the array. The smallest interval is allocated 255 interpolated values
* (the maximum number of unique in-between colors in a 24 bit color
* system), and all other intervals are allocated
* size = (255 * the ratio of their size to the smallest interval).
*
* This scheme expedites a speedy retrieval because the colors are
* distributed along the array according to their user-specified
* distribution. All that is needed is a relative index from 0 to 1.
*
* The only problem with this method is that the possibility exists for
* the array size to balloon in the case where there is a
* disproportionately small gradient interval. In this case the other
* intervals will be allocated huge space, but much of that data is
* redundant. We thus need to use the space conserving scheme below.
*
* @param Imin the size of the smallest interval
*/
private void calculateSingleArrayGradient(Color[] colors, float Imin) {
// set the flag so we know later it is a simple (fast) lookup
isSimpleLookup = true;
// 2 colors to interpolate
int rgb1, rgb2;
//the eventual size of the single array
int gradientsTot = 1;
// for every interval (transition between 2 colors)
for (int i = 0; i < gradients.length; i++) {
// create an array whose size is based on the ratio to the
// smallest interval
int nGradients = (int)((normalizedIntervals[i]/Imin)*255f);
gradientsTot += nGradients;
gradients[i] = new int[nGradients];
// the 2 colors (keyframes) to interpolate between
rgb1 = colors[i].getRGB();
rgb2 = colors[i+1].getRGB();
// fill this array with the colors in between rgb1 and rgb2
interpolate(rgb1, rgb2, gradients[i]);
// if the colors are opaque, transparency should still
// be 0xff000000
transparencyTest &= rgb1;
transparencyTest &= rgb2;
}
// put all gradients in a single array
gradient = new int[gradientsTot];
int curOffset = 0;
for (int i = 0; i < gradients.length; i++){
System.arraycopy(gradients[i], 0, gradient,
curOffset, gradients[i].length);
curOffset += gradients[i].length;
}
gradient[gradient.length-1] = colors[colors.length-1].getRGB();
// if interpolation occurred in Linear RGB space, convert the
// gradients back to sRGB using the lookup table
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
for (int i = 0; i < gradient.length; i++) {
gradient[i] = convertEntireColorLinearRGBtoSRGB(gradient[i]);
}
}
fastGradientArraySize = gradient.length - 1;
}
/**
* SLOW LOOKUP METHOD
*
* This method calculates the gradient color values for each interval and
* places each into its own 255 size array. The arrays are stored in
* gradients[][]. (255 is used because this is the maximum number of
* unique colors between 2 arbitrary colors in a 24 bit color system.)
*
* This method uses the minimum amount of space (only 255 * number of
* intervals), but it aggravates the lookup procedure, because now we
* have to find out which interval to select, then calculate the index
* within that interval. This causes a significant performance hit,
* because it requires this calculation be done for every point in
* the rendering loop.
*
* For those of you who are interested, this is a classic example of the
* time-space tradeoff.
*/
private void calculateMultipleArrayGradient(Color[] colors) {
// set the flag so we know later it is a non-simple lookup
isSimpleLookup = false;
// 2 colors to interpolate
int rgb1, rgb2;
// for every interval (transition between 2 colors)
for (int i = 0; i < gradients.length; i++){
// create an array of the maximum theoretical size for
// each interval
gradients[i] = new int[GRADIENT_SIZE];
// get the the 2 colors
rgb1 = colors[i].getRGB();
rgb2 = colors[i+1].getRGB();
// fill this array with the colors in between rgb1 and rgb2
interpolate(rgb1, rgb2, gradients[i]);
// if the colors are opaque, transparency should still
// be 0xff000000
transparencyTest &= rgb1;
transparencyTest &= rgb2;
}
// if interpolation occurred in Linear RGB space, convert the
// gradients back to SRGB using the lookup table
if (colorSpace == ColorSpaceType.LINEAR_RGB) {
for (int j = 0; j < gradients.length; j++) {
for (int i = 0; i < gradients[j].length; i++) {
gradients[j][i] =
convertEntireColorLinearRGBtoSRGB(gradients[j][i]);
}
}
}
}
/**
* Yet another helper function. This one linearly interpolates between
* 2 colors, filling up the output array.
*
* @param rgb1 the start color
* @param rgb2 the end color
* @param output the output array of colors; must not be null
*/
private void interpolate(int rgb1, int rgb2, int[] output) {
// color components
int a1, r1, g1, b1, da, dr, dg, db;
// step between<SUF>
float stepSize = 1.0f / output.length;
// extract color components from packed integer
a1 = (rgb1 >> 24) & 0xff;
r1 = (rgb1 >> 16) & 0xff;
g1 = (rgb1 >> 8) & 0xff;
b1 = (rgb1 ) & 0xff;
// calculate the total change in alpha, red, green, blue
da = ((rgb2 >> 24) & 0xff) - a1;
dr = ((rgb2 >> 16) & 0xff) - r1;
dg = ((rgb2 >> 8) & 0xff) - g1;
db = ((rgb2 ) & 0xff) - b1;
// for each step in the interval calculate the in-between color by
// multiplying the normalized current position by the total color
// change (0.5 is added to prevent truncation round-off error)
for (int i = 0; i < output.length; i++) {
output[i] =
(((int) ((a1 + i * da * stepSize) + 0.5) << 24)) |
(((int) ((r1 + i * dr * stepSize) + 0.5) << 16)) |
(((int) ((g1 + i * dg * stepSize) + 0.5) << 8)) |
(((int) ((b1 + i * db * stepSize) + 0.5) ));
}
}
/**
* Yet another helper function. This one extracts the color components
* of an integer RGB triple, converts them from LinearRGB to SRGB, then
* recompacts them into an int.
*/
private int convertEntireColorLinearRGBtoSRGB(int rgb) {
// color components
int a1, r1, g1, b1;
// extract red, green, blue components
a1 = (rgb >> 24) & 0xff;
r1 = (rgb >> 16) & 0xff;
g1 = (rgb >> 8) & 0xff;
b1 = (rgb ) & 0xff;
// use the lookup table
r1 = LinearRGBtoSRGB[r1];
g1 = LinearRGBtoSRGB[g1];
b1 = LinearRGBtoSRGB[b1];
// re-compact the components
return ((a1 << 24) |
(r1 << 16) |
(g1 << 8) |
(b1 ));
}
/**
* Helper function to index into the gradients array. This is necessary
* because each interval has an array of colors with uniform size 255.
* However, the color intervals are not necessarily of uniform length, so
* a conversion is required.
*
* @param position the unmanipulated position, which will be mapped
* into the range 0 to 1
* @returns integer color to display
*/
protected final int indexIntoGradientsArrays(float position) {
// first, manipulate position value depending on the cycle method
if (cycleMethod == CycleMethod.NO_CYCLE) {
if (position > 1) {
// upper bound is 1
position = 1;
} else if (position < 0) {
// lower bound is 0
position = 0;
}
} else if (cycleMethod == CycleMethod.REPEAT) {
// get the fractional part
// (modulo behavior discards integer component)
position = position - (int)position;
//position should now be between -1 and 1
if (position < 0) {
// force it to be in the range 0-1
position = position + 1;
}
} else { // cycleMethod == CycleMethod.REFLECT
if (position < 0) {
// take absolute value
position = -position;
}
// get the integer part
int part = (int)position;
// get the fractional part
position = position - part;
if ((part & 1) == 1) {
// integer part is odd, get reflected color instead
position = 1 - position;
}
}
// now, get the color based on this 0-1 position...
if (isSimpleLookup) {
// easy to compute: just scale index by array size
return gradient[(int)(position * fastGradientArraySize)];
} else {
// more complicated computation, to save space
// for all the gradient interval arrays
for (int i = 0; i < gradients.length; i++) {
if (position < fractions[i+1]) {
// this is the array we want
float delta = position - fractions[i];
// this is the interval we want
int index = (int)((delta / normalizedIntervals[i])
* (GRADIENT_SIZE_INDEX));
return gradients[i][index];
}
}
}
return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX];
}
/**
* Helper function to convert a color component in sRGB space to linear
* RGB space. Used to build a static lookup table.
*/
private static int convertSRGBtoLinearRGB(int color) {
float input, output;
input = color / 255.0f;
if (input <= 0.04045f) {
output = input / 12.92f;
} else {
output = (float)Math.pow((input + 0.055) / 1.055, 2.4);
}
return Math.round(output * 255.0f);
}
/**
* Helper function to convert a color component in linear RGB space to
* SRGB space. Used to build a static lookup table.
*/
private static int convertLinearRGBtoSRGB(int color) {
float input, output;
input = color/255.0f;
if (input <= 0.0031308) {
output = input * 12.92f;
} else {
output = (1.055f *
((float) Math.pow(input, (1.0 / 2.4)))) - 0.055f;
}
return Math.round(output * 255.0f);
}
/**
* {@inheritDoc}
*/
public final Raster getRaster(int x, int y, int w, int h) {
// If working raster is big enough, reuse it. Otherwise,
// build a large enough new one.
Raster raster = saved;
if (raster == null ||
raster.getWidth() < w || raster.getHeight() < h)
{
raster = getCachedRaster(model, w, h);
saved = raster;
}
// Access raster internal int array. Because we use a DirectColorModel,
// we know the DataBuffer is of type DataBufferInt and the SampleModel
// is SinglePixelPackedSampleModel.
// Adjust for initial offset in DataBuffer and also for the scanline
// stride.
// These calls make the DataBuffer non-acceleratable, but the
// Raster is never Stable long enough to accelerate anyway...
DataBufferInt rasterDB = (DataBufferInt)raster.getDataBuffer();
int[] pixels = rasterDB.getData(0);
int off = rasterDB.getOffset();
int scanlineStride = ((SinglePixelPackedSampleModel)
raster.getSampleModel()).getScanlineStride();
int adjust = scanlineStride - w;
fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass
return raster;
}
protected abstract void fillRaster(int pixels[], int off, int adjust,
int x, int y, int w, int h);
/**
* Took this cacheRaster code from GradientPaint. It appears to recycle
* rasters for use by any other instance, as long as they are sufficiently
* large.
*/
private static synchronized Raster getCachedRaster(ColorModel cm,
int w, int h)
{
if (cm == cachedModel) {
if (cached != null) {
Raster ras = (Raster) cached.get();
if (ras != null &&
ras.getWidth() >= w &&
ras.getHeight() >= h)
{
cached = null;
return ras;
}
}
}
return cm.createCompatibleWritableRaster(w, h);
}
/**
* Took this cacheRaster code from GradientPaint. It appears to recycle
* rasters for use by any other instance, as long as they are sufficiently
* large.
*/
private static synchronized void putCachedRaster(ColorModel cm,
Raster ras)
{
if (cached != null) {
Raster cras = (Raster) cached.get();
if (cras != null) {
int cw = cras.getWidth();
int ch = cras.getHeight();
int iw = ras.getWidth();
int ih = ras.getHeight();
if (cw >= iw && ch >= ih) {
return;
}
if (cw * ch >= iw * ih) {
return;
}
}
}
cachedModel = cm;
cached = new WeakReference<Raster>(ras);
}
/**
* {@inheritDoc}
*/
public final void dispose() {
if (saved != null) {
putCachedRaster(model, saved);
saved = null;
}
}
/**
* {@inheritDoc}
*/
public final ColorModel getColorModel() {
return model;
}
}
|
44514_7 | /*
* Copyright (C) 2016 Luca Corbatto
*
* This file is part of the hsReisePlugin.
*
* The hsReisePlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The hsReisePlugin 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package reiseplugin.data;
import java.util.Observable;
/**
* Contains all information of a {@link reiseplugin.data.Rast Rast}.
* @author Luca Corbatto {@literal <[email protected]>}
*/
public class Rast extends Observable {
private int start;
private int ende;
private int erschöpfungProStunde;
private int überanstrengungProStunde;
/**
* Creates a new {@link reiseplugin.data.Rast Rast} with the given parameters.
* If you give start = 12 and ende = 14 that results in a {@link reiseplugin.data.Rast Rast} from
* 12:00 - 14:00.
* @param start The start hour.
* @param ende The end hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public Rast(int start, int ende, int erschöpfungProStunde, int überanstrengungProStunde) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
this.start = start;
this.ende = ende;
this.erschöpfungProStunde = erschöpfungProStunde;
this.überanstrengungProStunde = überanstrengungProStunde;
}
/**
* Returns the start hour.
* @return The start hour.
*/
public int getStart() {
return start;
}
/**
* Sets the start hour.
* @param start The start hour.
*/
public void setStart(int start) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.start != start) {
this.start = start;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the end hour.
* @return The end hour.
*/
public int getEnde() {
return ende;
}
/**
* Sets the end hour.
* @param ende The end hour.
*/
public void setEnde(int ende) {
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.ende != ende) {
this.ende = ende;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getErschöpfungProStunde() {
return erschöpfungProStunde;
}
/**
* Sets the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setErschöpfungProStunde(int erschöpfungProStunde) {
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.erschöpfungProStunde != erschöpfungProStunde) {
this.erschöpfungProStunde = erschöpfungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getÜberanstrengungProStunde() {
return überanstrengungProStunde;
}
/**
* Sets the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setÜberanstrengungProStunde(int überanstrengungProStunde) {
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.überanstrengungProStunde != überanstrengungProStunde) {
this.überanstrengungProStunde = überanstrengungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
* @param st The hour to test.
* @return true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
*/
public boolean matchStunde(int st) {
if(this.start > this.ende) {
// über nacht
return this.start <= st || st < this.ende;
} else {
// über tag
return this.start <= st && st < this.ende;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Rast{" + "start=" + this.start + ", ende=" + this.ende + ", ersch\u00f6pfungProStunde=" + this.erschöpfungProStunde + ", \u00fcberanstrengungProStunde=" + this.überanstrengungProStunde + '}';
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + this.start;
hash = 37 * hash + this.ende;
hash = 37 * hash + this.erschöpfungProStunde;
hash = 37 * hash + this.überanstrengungProStunde;
return hash;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rast other = (Rast) obj;
if (this.start != other.start) {
return false;
}
if (this.ende != other.ende) {
return false;
}
if (this.erschöpfungProStunde != other.erschöpfungProStunde) {
return false;
}
if (this.überanstrengungProStunde != other.überanstrengungProStunde) {
return false;
}
return true;
}
} | targodan/hsReisePlugin | src/main/java/reiseplugin/data/Rast.java | 2,258 | /**
* Returns the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/ | block_comment | nl | /*
* Copyright (C) 2016 Luca Corbatto
*
* This file is part of the hsReisePlugin.
*
* The hsReisePlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The hsReisePlugin 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package reiseplugin.data;
import java.util.Observable;
/**
* Contains all information of a {@link reiseplugin.data.Rast Rast}.
* @author Luca Corbatto {@literal <[email protected]>}
*/
public class Rast extends Observable {
private int start;
private int ende;
private int erschöpfungProStunde;
private int überanstrengungProStunde;
/**
* Creates a new {@link reiseplugin.data.Rast Rast} with the given parameters.
* If you give start = 12 and ende = 14 that results in a {@link reiseplugin.data.Rast Rast} from
* 12:00 - 14:00.
* @param start The start hour.
* @param ende The end hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public Rast(int start, int ende, int erschöpfungProStunde, int überanstrengungProStunde) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
this.start = start;
this.ende = ende;
this.erschöpfungProStunde = erschöpfungProStunde;
this.überanstrengungProStunde = überanstrengungProStunde;
}
/**
* Returns the start hour.
* @return The start hour.
*/
public int getStart() {
return start;
}
/**
* Sets the start hour.
* @param start The start hour.
*/
public void setStart(int start) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.start != start) {
this.start = start;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the end hour.
* @return The end hour.
*/
public int getEnde() {
return ende;
}
/**
* Sets the end hour.
* @param ende The end hour.
*/
public void setEnde(int ende) {
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.ende != ende) {
this.ende = ende;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Erschöpfung<SUF>*/
public int getErschöpfungProStunde() {
return erschöpfungProStunde;
}
/**
* Sets the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setErschöpfungProStunde(int erschöpfungProStunde) {
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.erschöpfungProStunde != erschöpfungProStunde) {
this.erschöpfungProStunde = erschöpfungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getÜberanstrengungProStunde() {
return überanstrengungProStunde;
}
/**
* Sets the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setÜberanstrengungProStunde(int überanstrengungProStunde) {
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.überanstrengungProStunde != überanstrengungProStunde) {
this.überanstrengungProStunde = überanstrengungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
* @param st The hour to test.
* @return true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
*/
public boolean matchStunde(int st) {
if(this.start > this.ende) {
// über nacht
return this.start <= st || st < this.ende;
} else {
// über tag
return this.start <= st && st < this.ende;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Rast{" + "start=" + this.start + ", ende=" + this.ende + ", ersch\u00f6pfungProStunde=" + this.erschöpfungProStunde + ", \u00fcberanstrengungProStunde=" + this.überanstrengungProStunde + '}';
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + this.start;
hash = 37 * hash + this.ende;
hash = 37 * hash + this.erschöpfungProStunde;
hash = 37 * hash + this.überanstrengungProStunde;
return hash;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rast other = (Rast) obj;
if (this.start != other.start) {
return false;
}
if (this.ende != other.ende) {
return false;
}
if (this.erschöpfungProStunde != other.erschöpfungProStunde) {
return false;
}
if (this.überanstrengungProStunde != other.überanstrengungProStunde) {
return false;
}
return true;
}
} |
134937_8 | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class StryktipsPanel extends JPanel {
JPanel pnlEast = new JPanel();
JPanel pnlCenter = new JPanel();
JPanel pnlSouth = new JPanel();
JPanel pnlNorth = new JPanel();
JPanel pnlNorthNorth = new JPanel();
JPanel pnlNorthSouth = new JPanel();
JPanel pnlNorthSouthRight = new JPanel();
JLabel jblHeaderMatch = new JLabel("");
JLabel jblHeaderProcent = new JLabel("Streckade %");
JLabel jblHeaderOdds = new JLabel("Odds från SS");
JLabel jblHeaderDiffs = new JLabel("Över/under streckat");
JPanel pnlCenterLeft = new JPanel();
JPanel pnlCenterRight = new JPanel();
JPanel[] pnlGames = new JPanel[13];
JPanel[] pnlCheckBoxes = new JPanel[13];
JPanel[] pnlProcents = new JPanel[13];
JPanel[] pnlDiffs = new JPanel[13];
JPanel[] pnlOddses = new JPanel[13];
Checkbox[][] checkBoxes = new Checkbox[13][3];
JLabel jblTitle = new JLabel("<html><div style='text-align: center;'>" + "VECKANS OMGÅNG" + "</div></html>");
JLabel jblTurnOver = new JLabel();
JLabel[][] lblProcents = new JLabel[13][3];
JLabel[][] lblOddses = new JLabel[13][3];
JLabel[][] lblDiffs = new JLabel[13][3];
JPanel pnlCheckBox = new JPanel();
JPanel pnlProcent = new JPanel();
JPanel pnlDiff = new JPanel();
JPanel pnlOdds = new JPanel();
JTextField tfOdds = new JTextField();
JTextArea taResult = new JTextArea();
JButton btnDone = new JButton("Convert");
Controller controller;
Random rand = new Random();
private final int GAP = 0;
private Font font = new Font("SansSerif", Font.BOLD, 14);
private Font fontTitle = new Font("Arial", Font.BOLD, 20);
private Font fontTurnOver = new Font("Arial", Font.BOLD, 10);
private Font fontHeader = new Font("Arial", Font.BOLD, 14);
public StryktipsPanel() {
controller = new Controller(this);
setPreferredSize(new Dimension(800,500));
setLayout(new BorderLayout());
pnlSouth.setPreferredSize(new Dimension(0,20));
// pnlNorth.setBackground(Color.WHITE);
// pnlCenter.setBackground(Color.RED);
// pnlSouth.setBackground(Color.GREEN);
//panel north
pnlNorth.setPreferredSize(new Dimension(0,100));
pnlNorth.setLayout(new GridLayout(2,1));
pnlNorthSouth.setLayout(new GridLayout(1, 2));
pnlNorthSouthRight.setLayout(new GridLayout(1,3));
pnlNorthSouthRight.add(jblHeaderProcent);
pnlNorthSouthRight.add(jblHeaderOdds);
pnlNorthSouthRight.add(jblHeaderDiffs);
pnlNorthSouth.add(jblHeaderMatch);
pnlNorthSouth.add(pnlNorthSouthRight);
pnlNorth.add(pnlNorthNorth);
pnlNorth.add(pnlNorthSouth);
jblTitle.setFont(fontTitle);
pnlNorthNorth.add(jblTitle);
//panel center, includes gridlayout
pnlCenter.setLayout(new GridLayout(1,2));
pnlCenterLeft.setLayout(new GridLayout(13,1,GAP,GAP));
pnlCheckBox.setLayout(new GridLayout(13,1,GAP,GAP));
pnlProcent.setLayout(new GridLayout(13,3,GAP,GAP));
pnlDiff.setLayout(new GridLayout(13,3,GAP,GAP));
pnlOdds.setLayout(new GridLayout(13,1,GAP,GAP));
pnlCenterRight.setLayout(new GridLayout(1,3));
pnlCenterRight.setBackground(Color.darkGray);
initializePanels();
setGamePanels();
pnlCenter.add(pnlCenterLeft);
pnlCenter.add(pnlCenterRight);
//panel south, toggle buttons should be here
jblTurnOver.setFont(fontTurnOver);
pnlSouth.add(jblTurnOver);
add(pnlSouth, BorderLayout.SOUTH);
add(pnlNorth, BorderLayout.NORTH);
add(pnlCenter);
AL listener = new AL();
controller.getData();
}
public void updateAllPanels(String header, String turnOver, String[] games, String[][] procents, String[][] odds, int diffs[][]) {
jblTitle.setText(header);
jblTurnOver.setText("Omsättning: " + turnOver);
for(int i = 0; i < 13; i++) {
pnlGames[i].add(new JLabel(games[i]));
for(int j = 0; j < 3; j++) {
lblProcents[i][j].setText(procents[i][j]+"%");
lblOddses[i][j].setText(odds[i][j]);
lblDiffs[i][j].setText(diffs[i][j] + "");
//lblOddses[i][j].setBackground(Color.BLUE);
//lblOddses[i][j].setOpaque(true);
}
}
}
public void updateProcentPanel() {
}
public void updateOddsPanel() {
}
public void updateDiffPanel(double[][] diffs) {
for(int i = 0; i < diffs.length; i++) {
for (int j = 0; j < diffs[0].length; j++) {
//lblDiffs[i][j].setText(diffs[i][j] + "");
lblDiffs[i][j].setBackground(getColor(diffs[i][j]));
}
}
}
/**
* filling panels with objects
*/
private void initializePanels() {
pnlCenterRight.add(pnlProcent);
pnlCenterRight.add(pnlOdds);
pnlCenterRight.add(pnlDiff);
for(int i = 0; i < 13; i++) {
pnlGames[i] = new JPanel();
pnlCheckBoxes[i] = new JPanel();
pnlProcents[i] = new JPanel();
pnlDiffs[i] = new JPanel();
pnlOddses[i] = new JPanel();
for(int j = 0; j < 3; j++) {
checkBoxes[i][j] = new Checkbox();
JLabel tempLbl = new JLabel();
//tempLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
lblProcents[i][j] = tempLbl;
lblOddses[i][j] = new JLabel("x.00");
lblDiffs[i][j] = new JLabel("15");
lblDiffs[i][j].setOpaque(true);
// lblProcents[i][j].setBackground(new Color((int)(Math.random() * 0x1000000)));
lblProcents[i][j].setPreferredSize(new Dimension(35,20));
lblOddses[i][j].setPreferredSize(new Dimension(35,20));
lblDiffs[i][j].setPreferredSize(new Dimension(35,20));
lblOddses[i][j].setOpaque(true);
pnlCheckBoxes[i].add(checkBoxes[i][j]);
pnlProcents[i].add(lblProcents[i][j]);
pnlOddses[i].add(lblOddses[i][j]);
pnlDiffs[i].add(lblDiffs[i][j]);
}
/* pnlGames[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlCheckBoxes[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlProcents[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlOddses[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
*/
pnlCenterLeft.add(pnlGames[i]);
pnlCheckBox.add(pnlCheckBoxes[i]);
pnlProcent.add(pnlProcents[i]);
pnlOdds.add(pnlOddses[i]);
pnlDiff.add(pnlDiffs[i]);
}
}
private void setGamePanels() {
}
private class AL implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnDone) {
//double odds = Double.parseDouble(tfOdds.getText().toString());
//controller.convertOddsToProbability(odds);
int probability = Integer.parseInt(tfOdds.getText().toString());
controller.convertProbabilityToOdds(probability);
}
}
}
public Color getColor(double power)
{
//Where "power" is a number between 0.0 and 1.0. 0.0 will return a bright red, 1.0 will return a bright green.
double H = power * 0.34; // Hue (note 0.4 = Green, see huge chart below)
double S = 0.9; // Saturation
double B = 0.9; // Brightness
return Color.getHSBColor((float)H, (float)S, (float)B);
}
} | taurus84/stryktips-helper | src/StryktipsPanel.java | 2,778 | // Hue (note 0.4 = Green, see huge chart below) | line_comment | nl | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class StryktipsPanel extends JPanel {
JPanel pnlEast = new JPanel();
JPanel pnlCenter = new JPanel();
JPanel pnlSouth = new JPanel();
JPanel pnlNorth = new JPanel();
JPanel pnlNorthNorth = new JPanel();
JPanel pnlNorthSouth = new JPanel();
JPanel pnlNorthSouthRight = new JPanel();
JLabel jblHeaderMatch = new JLabel("");
JLabel jblHeaderProcent = new JLabel("Streckade %");
JLabel jblHeaderOdds = new JLabel("Odds från SS");
JLabel jblHeaderDiffs = new JLabel("Över/under streckat");
JPanel pnlCenterLeft = new JPanel();
JPanel pnlCenterRight = new JPanel();
JPanel[] pnlGames = new JPanel[13];
JPanel[] pnlCheckBoxes = new JPanel[13];
JPanel[] pnlProcents = new JPanel[13];
JPanel[] pnlDiffs = new JPanel[13];
JPanel[] pnlOddses = new JPanel[13];
Checkbox[][] checkBoxes = new Checkbox[13][3];
JLabel jblTitle = new JLabel("<html><div style='text-align: center;'>" + "VECKANS OMGÅNG" + "</div></html>");
JLabel jblTurnOver = new JLabel();
JLabel[][] lblProcents = new JLabel[13][3];
JLabel[][] lblOddses = new JLabel[13][3];
JLabel[][] lblDiffs = new JLabel[13][3];
JPanel pnlCheckBox = new JPanel();
JPanel pnlProcent = new JPanel();
JPanel pnlDiff = new JPanel();
JPanel pnlOdds = new JPanel();
JTextField tfOdds = new JTextField();
JTextArea taResult = new JTextArea();
JButton btnDone = new JButton("Convert");
Controller controller;
Random rand = new Random();
private final int GAP = 0;
private Font font = new Font("SansSerif", Font.BOLD, 14);
private Font fontTitle = new Font("Arial", Font.BOLD, 20);
private Font fontTurnOver = new Font("Arial", Font.BOLD, 10);
private Font fontHeader = new Font("Arial", Font.BOLD, 14);
public StryktipsPanel() {
controller = new Controller(this);
setPreferredSize(new Dimension(800,500));
setLayout(new BorderLayout());
pnlSouth.setPreferredSize(new Dimension(0,20));
// pnlNorth.setBackground(Color.WHITE);
// pnlCenter.setBackground(Color.RED);
// pnlSouth.setBackground(Color.GREEN);
//panel north
pnlNorth.setPreferredSize(new Dimension(0,100));
pnlNorth.setLayout(new GridLayout(2,1));
pnlNorthSouth.setLayout(new GridLayout(1, 2));
pnlNorthSouthRight.setLayout(new GridLayout(1,3));
pnlNorthSouthRight.add(jblHeaderProcent);
pnlNorthSouthRight.add(jblHeaderOdds);
pnlNorthSouthRight.add(jblHeaderDiffs);
pnlNorthSouth.add(jblHeaderMatch);
pnlNorthSouth.add(pnlNorthSouthRight);
pnlNorth.add(pnlNorthNorth);
pnlNorth.add(pnlNorthSouth);
jblTitle.setFont(fontTitle);
pnlNorthNorth.add(jblTitle);
//panel center, includes gridlayout
pnlCenter.setLayout(new GridLayout(1,2));
pnlCenterLeft.setLayout(new GridLayout(13,1,GAP,GAP));
pnlCheckBox.setLayout(new GridLayout(13,1,GAP,GAP));
pnlProcent.setLayout(new GridLayout(13,3,GAP,GAP));
pnlDiff.setLayout(new GridLayout(13,3,GAP,GAP));
pnlOdds.setLayout(new GridLayout(13,1,GAP,GAP));
pnlCenterRight.setLayout(new GridLayout(1,3));
pnlCenterRight.setBackground(Color.darkGray);
initializePanels();
setGamePanels();
pnlCenter.add(pnlCenterLeft);
pnlCenter.add(pnlCenterRight);
//panel south, toggle buttons should be here
jblTurnOver.setFont(fontTurnOver);
pnlSouth.add(jblTurnOver);
add(pnlSouth, BorderLayout.SOUTH);
add(pnlNorth, BorderLayout.NORTH);
add(pnlCenter);
AL listener = new AL();
controller.getData();
}
public void updateAllPanels(String header, String turnOver, String[] games, String[][] procents, String[][] odds, int diffs[][]) {
jblTitle.setText(header);
jblTurnOver.setText("Omsättning: " + turnOver);
for(int i = 0; i < 13; i++) {
pnlGames[i].add(new JLabel(games[i]));
for(int j = 0; j < 3; j++) {
lblProcents[i][j].setText(procents[i][j]+"%");
lblOddses[i][j].setText(odds[i][j]);
lblDiffs[i][j].setText(diffs[i][j] + "");
//lblOddses[i][j].setBackground(Color.BLUE);
//lblOddses[i][j].setOpaque(true);
}
}
}
public void updateProcentPanel() {
}
public void updateOddsPanel() {
}
public void updateDiffPanel(double[][] diffs) {
for(int i = 0; i < diffs.length; i++) {
for (int j = 0; j < diffs[0].length; j++) {
//lblDiffs[i][j].setText(diffs[i][j] + "");
lblDiffs[i][j].setBackground(getColor(diffs[i][j]));
}
}
}
/**
* filling panels with objects
*/
private void initializePanels() {
pnlCenterRight.add(pnlProcent);
pnlCenterRight.add(pnlOdds);
pnlCenterRight.add(pnlDiff);
for(int i = 0; i < 13; i++) {
pnlGames[i] = new JPanel();
pnlCheckBoxes[i] = new JPanel();
pnlProcents[i] = new JPanel();
pnlDiffs[i] = new JPanel();
pnlOddses[i] = new JPanel();
for(int j = 0; j < 3; j++) {
checkBoxes[i][j] = new Checkbox();
JLabel tempLbl = new JLabel();
//tempLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
lblProcents[i][j] = tempLbl;
lblOddses[i][j] = new JLabel("x.00");
lblDiffs[i][j] = new JLabel("15");
lblDiffs[i][j].setOpaque(true);
// lblProcents[i][j].setBackground(new Color((int)(Math.random() * 0x1000000)));
lblProcents[i][j].setPreferredSize(new Dimension(35,20));
lblOddses[i][j].setPreferredSize(new Dimension(35,20));
lblDiffs[i][j].setPreferredSize(new Dimension(35,20));
lblOddses[i][j].setOpaque(true);
pnlCheckBoxes[i].add(checkBoxes[i][j]);
pnlProcents[i].add(lblProcents[i][j]);
pnlOddses[i].add(lblOddses[i][j]);
pnlDiffs[i].add(lblDiffs[i][j]);
}
/* pnlGames[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlCheckBoxes[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlProcents[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
pnlOddses[i].setBackground(new Color((int)(Math.random() * 0x1000000)));
*/
pnlCenterLeft.add(pnlGames[i]);
pnlCheckBox.add(pnlCheckBoxes[i]);
pnlProcent.add(pnlProcents[i]);
pnlOdds.add(pnlOddses[i]);
pnlDiff.add(pnlDiffs[i]);
}
}
private void setGamePanels() {
}
private class AL implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnDone) {
//double odds = Double.parseDouble(tfOdds.getText().toString());
//controller.convertOddsToProbability(odds);
int probability = Integer.parseInt(tfOdds.getText().toString());
controller.convertProbabilityToOdds(probability);
}
}
}
public Color getColor(double power)
{
//Where "power" is a number between 0.0 and 1.0. 0.0 will return a bright red, 1.0 will return a bright green.
double H = power * 0.34; // Hue (note<SUF>
double S = 0.9; // Saturation
double B = 0.9; // Brightness
return Color.getHSBColor((float)H, (float)S, (float)B);
}
} |
14078_1 | package domein;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import dto.SpelerDTO;
public class DomeinController{
private SpelerRepository spelerrepo;
private KaartRepository kaartrepo;
private EdeleRepository edelerepo;
private Speler speler;
private List<Speler> spelers;
private Spel spel = new Spel();
private static String padTaal ="src/talen/taal.properties";
static final Properties taal = new Properties();
static {
try {
taal.load(new FileInputStream(padTaal));
} catch (Exception e) {
e.printStackTrace();
}
};
//Dit is de constructor voor de klasse DomeinController.
public DomeinController(){
this.spelerrepo = new SpelerRepository();
this.kaartrepo = new KaartRepository();
this.edelerepo = new EdeleRepository();
}
//Deze methode start een spel
public void startSpel() {
this.spel = new Spel();
}
public void voegSpeler(String username, int geboortejaar)
{
spel.voegSpelerToe(spelerrepo.geefSpeler(username, geboortejaar));
}
//Deze methode registreert een nieuwe speler
public void registreer(String username, String voornaam, String achternaam, int geboortejaar) {
spelerrepo.voegToe(new Speler(geboortejaar, voornaam, achternaam, username, false));
}
//Deze methode geeft alle info van de speler terug.
public SpelerDTO geefSpeler() {
if(speler != null) {
return new SpelerDTO(speler.getGeboortejaar(), speler.getVoornaam(), speler.getAchternaam(), speler.getUsername(), speler.getScore(), speler.getEdelstenen(), speler.getKaarten());
}
return null;
}
//Deze methode geeft de score van de speler terug
public int geefScore() {
return speler.getScore();
}
//Deze methode controleert of het spel gedaan is.
public boolean isEindeSpel() {
return spel.isEindeSpel();
}
//Meld een speler aan, aan de hand van zijn username en geboortejaar.
public void meldAan(String username, int geboortejaar) {
speler = spelerrepo.geefSpeler(username, geboortejaar);
}
public boolean controleerSpeler(String username)
{
boolean antwoord =false;
if(spelerrepo.bestaatSpeler(username))
{
antwoord =true;
}
return antwoord;
}
public void infoSpeler(String taalKeuze)
{
spel.infoSpeler(taalKeuze);
}
public List geefKaartNiveau1(String taalkeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau1();
return pick3;
}
public List<Kaart> geefKaartNiveau2(String taalKeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau2();
return pick3;
}
public List<Kaart> geefKaartNiveau3(String taalKeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau3();
return pick3;
}
public List<Kaart> toonKaartenVanSpeler(Speler speler2) {
return speler2.getKaarten();
}
public List<Edele> geefEdelen(String taalkeuze)
{
List<Edele> pick4 = edelerepo.geefEdelen();
return pick4;
/*for (Edele edele : pick4) {
System.out.printf("%s %s", edele.getPrijs(), edele.getWaarde());
}*/
}
} | taylon-vandenbroecke/splendor | src/domein/DomeinController.java | 1,203 | //Deze methode start een spel | line_comment | nl | package domein;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import dto.SpelerDTO;
public class DomeinController{
private SpelerRepository spelerrepo;
private KaartRepository kaartrepo;
private EdeleRepository edelerepo;
private Speler speler;
private List<Speler> spelers;
private Spel spel = new Spel();
private static String padTaal ="src/talen/taal.properties";
static final Properties taal = new Properties();
static {
try {
taal.load(new FileInputStream(padTaal));
} catch (Exception e) {
e.printStackTrace();
}
};
//Dit is de constructor voor de klasse DomeinController.
public DomeinController(){
this.spelerrepo = new SpelerRepository();
this.kaartrepo = new KaartRepository();
this.edelerepo = new EdeleRepository();
}
//Deze methode<SUF>
public void startSpel() {
this.spel = new Spel();
}
public void voegSpeler(String username, int geboortejaar)
{
spel.voegSpelerToe(spelerrepo.geefSpeler(username, geboortejaar));
}
//Deze methode registreert een nieuwe speler
public void registreer(String username, String voornaam, String achternaam, int geboortejaar) {
spelerrepo.voegToe(new Speler(geboortejaar, voornaam, achternaam, username, false));
}
//Deze methode geeft alle info van de speler terug.
public SpelerDTO geefSpeler() {
if(speler != null) {
return new SpelerDTO(speler.getGeboortejaar(), speler.getVoornaam(), speler.getAchternaam(), speler.getUsername(), speler.getScore(), speler.getEdelstenen(), speler.getKaarten());
}
return null;
}
//Deze methode geeft de score van de speler terug
public int geefScore() {
return speler.getScore();
}
//Deze methode controleert of het spel gedaan is.
public boolean isEindeSpel() {
return spel.isEindeSpel();
}
//Meld een speler aan, aan de hand van zijn username en geboortejaar.
public void meldAan(String username, int geboortejaar) {
speler = spelerrepo.geefSpeler(username, geboortejaar);
}
public boolean controleerSpeler(String username)
{
boolean antwoord =false;
if(spelerrepo.bestaatSpeler(username))
{
antwoord =true;
}
return antwoord;
}
public void infoSpeler(String taalKeuze)
{
spel.infoSpeler(taalKeuze);
}
public List geefKaartNiveau1(String taalkeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau1();
return pick3;
}
public List<Kaart> geefKaartNiveau2(String taalKeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau2();
return pick3;
}
public List<Kaart> geefKaartNiveau3(String taalKeuze)
{
List<Kaart> pick3 = kaartrepo.geefKaartNiveau3();
return pick3;
}
public List<Kaart> toonKaartenVanSpeler(Speler speler2) {
return speler2.getKaarten();
}
public List<Edele> geefEdelen(String taalkeuze)
{
List<Edele> pick4 = edelerepo.geefEdelen();
return pick4;
/*for (Edele edele : pick4) {
System.out.printf("%s %s", edele.getPrijs(), edele.getWaarde());
}*/
}
} |
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 | 417 | /**
* @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);
}
}
|
74925_25 | package org.tbee.tesla;
/*-
* #%L
* TeslaAPI
* %%
* Copyright (C) 2020 - 2021 Tom Eugelink
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tbee.tesla.dto.ChargeState;
import org.tbee.tesla.dto.ClimateState;
import org.tbee.tesla.dto.DriveState;
import org.tbee.tesla.dto.GUISettings;
import org.tbee.tesla.dto.Tokens;
import org.tbee.tesla.dto.Vehicle;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.JavaNetCookieJar;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
/**
* A Java implementation of Tesla REST API based on https://www.teslaapi.io/
*
* This wrapper is stateful because it remembers the oauth tokens, and thus an instance can be used for one account at a time.
* The individual vehicles within an account are accessed as a parameter to the methods.
* This implementation tries to stay as close to Tesla's API as possible, with a few small additions:
* - There is a wakUp method that has a retry logic added, it verifies communication by trying to fetch the shift state.
* - The heatSeat method has an alias using enums for readability, because the seat numbering has a gap (0,1,2,4,5).
* - Commands interpret the response's reason to see if it actually is not an error; like "already_set" when trying to set a temperature.
*
* Example usage:
* TeslaAPI teslaAPI = new TeslaAPI();
* teslaAPI.login(TESLA_USERNAME, TESLA_PASSWORD, TESLA_MFA_PASSCODE); // or use setTokens
* List<Vehicle> vehicles = teslaAPI.getVehicles();
* String vehicleId = vehicles.get(0).id;
* teslaAPI.flashLights(vehicleId)
*/
public class TeslaAPI {
static final Logger logger = LoggerFactory.getLogger(TeslaAPI.class);
// API contants
static final String URL_BASE = "https://owner-api.teslamotors.com/";
static final String URL_VERSION = "api/1/";
static final String URL_VEHICLES = "vehicles/";
static final String HEADER_AUTHORIZATION = "Authorization";
// For HTTP
private final Gson gson = new Gson();
private final OkHttpClient okHttpClient;
private final MediaType JsonMediaType = MediaType.parse("application/json; charset=utf-8");
// State
private Tokens tokens = null;
private String authorizationHeader = null;
// For improved logging
private String logPrefix = "";
/**
*
*/
public TeslaAPI() {
// Create a cookie store
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
// Setup the logger
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new okhttp3.logging.HttpLoggingInterceptor.Logger() { // if we do not use a lambda here, the method log output will read "log(", which will make grepping easier if required
@Override
public void log(String s) {
logger.trace("{}{}", logPrefix, s);
}
});
logging.setLevel(Level.BODY);
// Initialize the HTTP client
okHttpClient = new OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(2, TimeUnit.MINUTES)
.cookieJar(new JavaNetCookieJar(cookieManager))
.addNetworkInterceptor(logging)
.build();
}
/**
*
* @param s
*/
public void setLogPrefix(String s) {
if (s == null) {
throw new IllegalArgumentException("Cannot be null");
}
logPrefix = s;
}
public String getLogPrefix() {
return logPrefix;
}
/**
* This semi-login only fetches and remembers the access and refresh tokens needed for further actions.
* You may also set these manually using setTokens
* In order to obtain the authorizationCode the user needs to complete the whole login process and extra the authorizationCode from the double redirects in the web browser flow.
* @param authorizationCode
* @return
*/
public Tokens login(String authorizationCode) {
Tokens tokens = new TeslaAuthLogin(okHttpClient, logPrefix).login(authorizationCode);
setTokens(tokens);
return tokens;
}
/**
* This login only fetches and remembers the access and refresh tokens needed for further actions.
* You may also set these manually using setTokens
* @param username
* @param password
* @param passcode
* @return
*/
public Tokens login(String username, String password, String passcode) {
Tokens tokens = new TeslaMFALogin(okHttpClient, logPrefix).login(username, password, passcode);
setTokens(tokens);
return tokens;
}
/**
* This login only fetches and remembers the access and refresh tokens needed for further actions.
* This is a non-MFA (multi factor authentication) login.
* You may also set these manually using setTokens
* @param username
* @param password
* @return
*/
public Tokens login(String username, String password) {
Tokens tokens = new TeslaNoMFALogin(okHttpClient, logPrefix).login(username, password);
setTokens(tokens);
return tokens;
}
/**
* This method fetches (and remembers/replaces) new access and refresh tokens
* @return
*/
public Tokens refreshTokens() {
Tokens tokens = new TeslaLoginHelper(okHttpClient, logPrefix).refreshTokens(this.tokens);
setTokens(tokens);
return tokens;
}
/**
* When we do not use the login method, provide the tokens manually.
* @param tokens
*/
public void setTokens(Tokens tokens) {
this.tokens = tokens;
logger.debug("using tokens: {}{}", logPrefix, tokens);
this.authorizationHeader = "Bearer " + tokens.accessToken;
}
public Tokens getTokens() {
return tokens;
}
/**
* @return
*/
public List<Vehicle> getVehicles() {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.get()
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
if (!response.isSuccessful()) {
return Collections.emptyList();
}
// Parse the result and build a list of vehicles
// {"response":[{"id":242342423,"vehicle_id":123123123123,"vin":"12312312321","display_name":"Tarah", ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
List<Vehicle> vehicles = new ArrayList<>();
responseJsonObject.get("response").getAsJsonArray().forEach((jsonElement) -> vehicles.add(new Vehicle(jsonElement.getAsJsonObject())));
return vehicles;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Get a vehicle by its VIN
* @param vin
* @return
*/
public Vehicle getVehicleByVIN(String vin) {
List<Vehicle> vehicles = getVehicles();
Vehicle vehicle = null;
for (Vehicle vehicleCandidate : vehicles) {
if (vin.equals(vehicleCandidate.vin)) {
vehicle = vehicleCandidate;
break;
}
}
return vehicle;
}
/**
* @return null if everything is ok, or an error string if not
*/
public String wakeUp(String vehicleId) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/wake_up")
.header(HEADER_AUTHORIZATION, authorizationHeader)
.post(RequestBody.create("", JsonMediaType))
.build();
try (
Response response = okHttpClient.newCall(request).execute();
) {
return response.isSuccessful() ? null : "request failed with HTTP " + response.code();
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Combine wakeup and getDriveState to make sure the car really is wake, and retry until successful or the time expires.
* NOTE: If a drive state is returned, but it does not contain a shift state, and the time expires, P is assumed.
* @return the shiftState (because that often determines follow up actions; don't meddle with the car when it is driving)
*/
public String wakeUp(String vehicleId, int retryDurationInMS, int sleepTimeInMS) {
long retryUntil = System.currentTimeMillis() + retryDurationInMS;
// until we're satified
int attemptCnt = 0;
while (true) {
long now = System.currentTimeMillis();
// attempt wakeup
logger.debug("{}Waking up {}, attempt={}", logPrefix, vehicleId, ++attemptCnt);
String wakeUp = wakeUp(vehicleId);
// get drive state
DriveState driveState = getDriveState(vehicleId);
String shiftState = (driveState == null ? null : driveState.shiftState);
logger.debug("{}Waking up {}, wakeUp={}, shiftState={}, driveState={}", logPrefix, vehicleId, wakeUp, shiftState, driveState);
// If shift state is set, we're done
if (!isEmpty(shiftState)) {
logger.debug("{}Waking up {} succes, shiftState={}", logPrefix, vehicleId, shiftState);
return shiftState;
}
// If we got a driveState, but the shift state is empty, and max time expired, assume 'P'
if (driveState != null && isEmpty(shiftState) && now > retryUntil) {
logger.debug("{}Waking up {}, shiftState is empty, maxTimeExpired => assuming P", logPrefix, vehicleId);
return "P";
}
// if max time expired, exit
if (now > retryUntil) {
logger.debug("{}Waking up {} failed", logPrefix, vehicleId);
return null;
}
// Sleep 5 seconds
sleep(sleepTimeInMS);
}
}
/**
* @return null if everything is ok, or an error string if not
*/
public String flashLights(String vehicleId) {
return doCommand(vehicleId, "flash_lights", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String startAutoConditioning(String vehicleId) {
return doCommand(vehicleId, "auto_conditioning_start", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String stopAutoConditioning(String vehicleId) {
return doCommand(vehicleId, "auto_conditioning_stop", "");
}
/**
* The parameters are always in celsius, regardless of the region the car is in or the display settings of the car.
* @return null if everything is ok, or an error string if not
*/
public String setTemps(String vehicleId, double driverTemp, double passengerTemp) {
return doCommand(vehicleId, "set_temps", String.format(Locale.US, "{\"driver_temp\" : \"%3.1f\", \"passenger_temp\" : \"%3.1f\"}",driverTemp, passengerTemp));
}
/**
* Set temperature, but use GUI setting to convert to value to celcius (as required by setTemps) if unit is not specified
* @return null if everything is ok, or an error string if not
*/
public String setTempsWithConversion(String vehicleId, double driverTemp, double passengerTemp, String unit) {
// If the unit is not specified, get it from the GUI settings
if (unit == null) {
GUISettings guiSettings = getGUISettings(vehicleId);
unit = guiSettings.guiTemperatureUnits;
}
if (unit != null) {
unit = unit.toUpperCase();
}
// The parameters of the API call are always in celsius, so we need to convert F to C for example
if ("F".equals(unit)) {
driverTemp = convertF2C(driverTemp);
passengerTemp = convertF2C(passengerTemp);
}
// do it
return setTemps(vehicleId, driverTemp, passengerTemp);
}
private double convertF2C(double f) {
double unrounded = (f - 32.0) * (5.0/9.0); // 0°C = (32°F − 32) × 5/9
double rounded = BigDecimal.valueOf(unrounded).setScale(1, RoundingMode.HALF_UP).doubleValue();
return rounded;
}
/**
* The parameters are always in celsius, regardless of the region the car is in or the display settings of the car.
* @return null if everything is ok, or an error string if not
*/
public String setPreconditioningMax(String vehicleId, boolean on) {
return doCommand(vehicleId, "set_preconditioning_max", String.format(Locale.US, "{\"on\" : \"%s\"}","" + on));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String startCharging(String vehicleId) {
return doCommand(vehicleId, "charge_start", "", "charging", "complete");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String stopCharging(String vehicleId) {
return doCommand(vehicleId, "charge_stop", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String setChargeLimit(String vehicleId, int percent) {
if (percent < 1 || percent > 100) {
throw new IllegalArgumentException("Percent must be between 0 and 100");
}
return doCommand(vehicleId, "set_charge_limit", String.format("{\"percent\" : \"%d\"}", percent));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String lockDoors(String vehicleId) {
return doCommand(vehicleId, "door_lock", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String unlockDoors(String vehicleId) {
return doCommand(vehicleId, "door_unlock", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String setSentryMode(String vehicleId, boolean state) {
return doCommand(vehicleId, "set_sentry_mode", String.format("{\"on\" : \"%s\"}", "" + state));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String windowControl(String vehicleId, String command) {
return doCommand(vehicleId, "window_control", String.format("{\"command\" : \"%s\"}", "" + command));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String sunRoofControl(String vehicleId, String state) {
return doCommand(vehicleId, "sun_roof_control", String.format("{\"state\" : \"%s\"}", "" + state));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSeat(String vehicleId, int heater, int level) {
return doCommand(vehicleId, "remote_seat_heater_request", String.format("{\"heater\" : \"%s\", \"level\" : \"%s\"}", "" + heater, "" + level));
}
enum HeatSeat {
DRIVER(0),
PASSENGER(1),
REARLEFT(2),
REARCENTER(4),
REARRIGHT(5);
private final int nr;
private HeatSeat(int nr) {
this.nr = nr;
}
}
enum HeatSeatLevel {
OFF(0),
LOW(1),
MEDIUM(2),
HIGH(3);
private final int nr;
private HeatSeatLevel(int nr) {
this.nr = nr;
}
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSeat(String vehicleId, HeatSeat heatSeat, HeatSeatLevel heatSeatLevel) {
return heatSeat(vehicleId, heatSeat.nr, heatSeatLevel.nr);
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSteeringWheel(String vehicleId, boolean state) {
return doCommand(vehicleId, "remote_steering_wheel_heater_request", String.format("{\"on\" : \"%s\"}", "" + state));
}
/*
*
*/
private String doCommand(String vehicleId, String command, String bodyContent) {
return doCommand(vehicleId, command, bodyContent, new String[] {});
}
/*
*
*/
private String doCommand(String vehicleId, String command, String bodyContent, String... okReasons) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/command/" + command)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.post(RequestBody.create(bodyContent, JsonMediaType))
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
int code = response.code();
if (!response.isSuccessful()) {
logger.warn("{}response is not succesful: {}", logPrefix, response);
return "request failed with HTTP " + code;
}
// Parse the result and build a list of vehicles
// {"response":{"result": true,,"reason": ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
responseJsonObject = responseJsonObject.get("response").getAsJsonObject();
boolean result = responseJsonObject.get("result").getAsBoolean();
String reason = responseJsonObject.get("reason").getAsString();
if (reason.equals("already_set") || Arrays.asList(okReasons).contains(reason)) {
reason = "";
}
if (!result) logger.warn(reason + ": " + request + " " + bodyContent + " " + response + " " + responseBodyContent);
if (isEmpty(reason)) {
reason = null;
}
return reason;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @return null if request had an error
*
*/
public ChargeState getChargeState(String vehicleId) {
return getState(vehicleId, "charge_state", ChargeState.class);
}
/**
* @return null if request had an error
*
*/
public ClimateState getClimateState(String vehicleId) {
return getState(vehicleId, "climate_state", ClimateState.class);
}
/**
* @return null if request had an error
*
*/
public DriveState getDriveState(String vehicleId) {
return getState(vehicleId, "drive_state", DriveState.class);
}
/**
* @return null if request had an error
*
*/
public GUISettings getGUISettings(String vehicleId) {
return getState(vehicleId, "gui_settings", GUISettings.class);
}
/**
* @return null if request had an error
*
*/
private <T> T getState(String vehicleId, String urlSuffix, Class<T> clazz) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/data_request/" + urlSuffix)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.get()
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
if (!response.isSuccessful()) {
logger.warn("{}response is not succesful: {}", logPrefix, response);
return null;
}
// Parse the result and build a list of vehicles
// {"response":{"gps_as_of":1565873014,"heading":71,"latitude":51.823154,"longitude":5.786151,"native_latitu ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
responseJsonObject = responseJsonObject.get("response").getAsJsonObject();
return clazz.getConstructor(JsonObject.class).newInstance(responseJsonObject);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/*
*
*/
private void doTokensCheck() {
if (tokens == null) {
throw new RuntimeException("No login or setTokens was done.");
}
}
/*
*
* @param s
* @return
*/
private boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
/*
*
*/
static private void sleep(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| tbee/teslaApi | api/src/main/java/org/tbee/tesla/TeslaAPI.java | 6,596 | // Sleep 5 seconds | line_comment | nl | package org.tbee.tesla;
/*-
* #%L
* TeslaAPI
* %%
* Copyright (C) 2020 - 2021 Tom Eugelink
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tbee.tesla.dto.ChargeState;
import org.tbee.tesla.dto.ClimateState;
import org.tbee.tesla.dto.DriveState;
import org.tbee.tesla.dto.GUISettings;
import org.tbee.tesla.dto.Tokens;
import org.tbee.tesla.dto.Vehicle;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.JavaNetCookieJar;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
/**
* A Java implementation of Tesla REST API based on https://www.teslaapi.io/
*
* This wrapper is stateful because it remembers the oauth tokens, and thus an instance can be used for one account at a time.
* The individual vehicles within an account are accessed as a parameter to the methods.
* This implementation tries to stay as close to Tesla's API as possible, with a few small additions:
* - There is a wakUp method that has a retry logic added, it verifies communication by trying to fetch the shift state.
* - The heatSeat method has an alias using enums for readability, because the seat numbering has a gap (0,1,2,4,5).
* - Commands interpret the response's reason to see if it actually is not an error; like "already_set" when trying to set a temperature.
*
* Example usage:
* TeslaAPI teslaAPI = new TeslaAPI();
* teslaAPI.login(TESLA_USERNAME, TESLA_PASSWORD, TESLA_MFA_PASSCODE); // or use setTokens
* List<Vehicle> vehicles = teslaAPI.getVehicles();
* String vehicleId = vehicles.get(0).id;
* teslaAPI.flashLights(vehicleId)
*/
public class TeslaAPI {
static final Logger logger = LoggerFactory.getLogger(TeslaAPI.class);
// API contants
static final String URL_BASE = "https://owner-api.teslamotors.com/";
static final String URL_VERSION = "api/1/";
static final String URL_VEHICLES = "vehicles/";
static final String HEADER_AUTHORIZATION = "Authorization";
// For HTTP
private final Gson gson = new Gson();
private final OkHttpClient okHttpClient;
private final MediaType JsonMediaType = MediaType.parse("application/json; charset=utf-8");
// State
private Tokens tokens = null;
private String authorizationHeader = null;
// For improved logging
private String logPrefix = "";
/**
*
*/
public TeslaAPI() {
// Create a cookie store
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
// Setup the logger
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new okhttp3.logging.HttpLoggingInterceptor.Logger() { // if we do not use a lambda here, the method log output will read "log(", which will make grepping easier if required
@Override
public void log(String s) {
logger.trace("{}{}", logPrefix, s);
}
});
logging.setLevel(Level.BODY);
// Initialize the HTTP client
okHttpClient = new OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(2, TimeUnit.MINUTES)
.cookieJar(new JavaNetCookieJar(cookieManager))
.addNetworkInterceptor(logging)
.build();
}
/**
*
* @param s
*/
public void setLogPrefix(String s) {
if (s == null) {
throw new IllegalArgumentException("Cannot be null");
}
logPrefix = s;
}
public String getLogPrefix() {
return logPrefix;
}
/**
* This semi-login only fetches and remembers the access and refresh tokens needed for further actions.
* You may also set these manually using setTokens
* In order to obtain the authorizationCode the user needs to complete the whole login process and extra the authorizationCode from the double redirects in the web browser flow.
* @param authorizationCode
* @return
*/
public Tokens login(String authorizationCode) {
Tokens tokens = new TeslaAuthLogin(okHttpClient, logPrefix).login(authorizationCode);
setTokens(tokens);
return tokens;
}
/**
* This login only fetches and remembers the access and refresh tokens needed for further actions.
* You may also set these manually using setTokens
* @param username
* @param password
* @param passcode
* @return
*/
public Tokens login(String username, String password, String passcode) {
Tokens tokens = new TeslaMFALogin(okHttpClient, logPrefix).login(username, password, passcode);
setTokens(tokens);
return tokens;
}
/**
* This login only fetches and remembers the access and refresh tokens needed for further actions.
* This is a non-MFA (multi factor authentication) login.
* You may also set these manually using setTokens
* @param username
* @param password
* @return
*/
public Tokens login(String username, String password) {
Tokens tokens = new TeslaNoMFALogin(okHttpClient, logPrefix).login(username, password);
setTokens(tokens);
return tokens;
}
/**
* This method fetches (and remembers/replaces) new access and refresh tokens
* @return
*/
public Tokens refreshTokens() {
Tokens tokens = new TeslaLoginHelper(okHttpClient, logPrefix).refreshTokens(this.tokens);
setTokens(tokens);
return tokens;
}
/**
* When we do not use the login method, provide the tokens manually.
* @param tokens
*/
public void setTokens(Tokens tokens) {
this.tokens = tokens;
logger.debug("using tokens: {}{}", logPrefix, tokens);
this.authorizationHeader = "Bearer " + tokens.accessToken;
}
public Tokens getTokens() {
return tokens;
}
/**
* @return
*/
public List<Vehicle> getVehicles() {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.get()
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
if (!response.isSuccessful()) {
return Collections.emptyList();
}
// Parse the result and build a list of vehicles
// {"response":[{"id":242342423,"vehicle_id":123123123123,"vin":"12312312321","display_name":"Tarah", ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
List<Vehicle> vehicles = new ArrayList<>();
responseJsonObject.get("response").getAsJsonArray().forEach((jsonElement) -> vehicles.add(new Vehicle(jsonElement.getAsJsonObject())));
return vehicles;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Get a vehicle by its VIN
* @param vin
* @return
*/
public Vehicle getVehicleByVIN(String vin) {
List<Vehicle> vehicles = getVehicles();
Vehicle vehicle = null;
for (Vehicle vehicleCandidate : vehicles) {
if (vin.equals(vehicleCandidate.vin)) {
vehicle = vehicleCandidate;
break;
}
}
return vehicle;
}
/**
* @return null if everything is ok, or an error string if not
*/
public String wakeUp(String vehicleId) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/wake_up")
.header(HEADER_AUTHORIZATION, authorizationHeader)
.post(RequestBody.create("", JsonMediaType))
.build();
try (
Response response = okHttpClient.newCall(request).execute();
) {
return response.isSuccessful() ? null : "request failed with HTTP " + response.code();
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Combine wakeup and getDriveState to make sure the car really is wake, and retry until successful or the time expires.
* NOTE: If a drive state is returned, but it does not contain a shift state, and the time expires, P is assumed.
* @return the shiftState (because that often determines follow up actions; don't meddle with the car when it is driving)
*/
public String wakeUp(String vehicleId, int retryDurationInMS, int sleepTimeInMS) {
long retryUntil = System.currentTimeMillis() + retryDurationInMS;
// until we're satified
int attemptCnt = 0;
while (true) {
long now = System.currentTimeMillis();
// attempt wakeup
logger.debug("{}Waking up {}, attempt={}", logPrefix, vehicleId, ++attemptCnt);
String wakeUp = wakeUp(vehicleId);
// get drive state
DriveState driveState = getDriveState(vehicleId);
String shiftState = (driveState == null ? null : driveState.shiftState);
logger.debug("{}Waking up {}, wakeUp={}, shiftState={}, driveState={}", logPrefix, vehicleId, wakeUp, shiftState, driveState);
// If shift state is set, we're done
if (!isEmpty(shiftState)) {
logger.debug("{}Waking up {} succes, shiftState={}", logPrefix, vehicleId, shiftState);
return shiftState;
}
// If we got a driveState, but the shift state is empty, and max time expired, assume 'P'
if (driveState != null && isEmpty(shiftState) && now > retryUntil) {
logger.debug("{}Waking up {}, shiftState is empty, maxTimeExpired => assuming P", logPrefix, vehicleId);
return "P";
}
// if max time expired, exit
if (now > retryUntil) {
logger.debug("{}Waking up {} failed", logPrefix, vehicleId);
return null;
}
// Sleep 5<SUF>
sleep(sleepTimeInMS);
}
}
/**
* @return null if everything is ok, or an error string if not
*/
public String flashLights(String vehicleId) {
return doCommand(vehicleId, "flash_lights", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String startAutoConditioning(String vehicleId) {
return doCommand(vehicleId, "auto_conditioning_start", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String stopAutoConditioning(String vehicleId) {
return doCommand(vehicleId, "auto_conditioning_stop", "");
}
/**
* The parameters are always in celsius, regardless of the region the car is in or the display settings of the car.
* @return null if everything is ok, or an error string if not
*/
public String setTemps(String vehicleId, double driverTemp, double passengerTemp) {
return doCommand(vehicleId, "set_temps", String.format(Locale.US, "{\"driver_temp\" : \"%3.1f\", \"passenger_temp\" : \"%3.1f\"}",driverTemp, passengerTemp));
}
/**
* Set temperature, but use GUI setting to convert to value to celcius (as required by setTemps) if unit is not specified
* @return null if everything is ok, or an error string if not
*/
public String setTempsWithConversion(String vehicleId, double driverTemp, double passengerTemp, String unit) {
// If the unit is not specified, get it from the GUI settings
if (unit == null) {
GUISettings guiSettings = getGUISettings(vehicleId);
unit = guiSettings.guiTemperatureUnits;
}
if (unit != null) {
unit = unit.toUpperCase();
}
// The parameters of the API call are always in celsius, so we need to convert F to C for example
if ("F".equals(unit)) {
driverTemp = convertF2C(driverTemp);
passengerTemp = convertF2C(passengerTemp);
}
// do it
return setTemps(vehicleId, driverTemp, passengerTemp);
}
private double convertF2C(double f) {
double unrounded = (f - 32.0) * (5.0/9.0); // 0°C = (32°F − 32) × 5/9
double rounded = BigDecimal.valueOf(unrounded).setScale(1, RoundingMode.HALF_UP).doubleValue();
return rounded;
}
/**
* The parameters are always in celsius, regardless of the region the car is in or the display settings of the car.
* @return null if everything is ok, or an error string if not
*/
public String setPreconditioningMax(String vehicleId, boolean on) {
return doCommand(vehicleId, "set_preconditioning_max", String.format(Locale.US, "{\"on\" : \"%s\"}","" + on));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String startCharging(String vehicleId) {
return doCommand(vehicleId, "charge_start", "", "charging", "complete");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String stopCharging(String vehicleId) {
return doCommand(vehicleId, "charge_stop", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String setChargeLimit(String vehicleId, int percent) {
if (percent < 1 || percent > 100) {
throw new IllegalArgumentException("Percent must be between 0 and 100");
}
return doCommand(vehicleId, "set_charge_limit", String.format("{\"percent\" : \"%d\"}", percent));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String lockDoors(String vehicleId) {
return doCommand(vehicleId, "door_lock", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String unlockDoors(String vehicleId) {
return doCommand(vehicleId, "door_unlock", "");
}
/**
* @return null if everything is ok, or an error string if not
*/
public String setSentryMode(String vehicleId, boolean state) {
return doCommand(vehicleId, "set_sentry_mode", String.format("{\"on\" : \"%s\"}", "" + state));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String windowControl(String vehicleId, String command) {
return doCommand(vehicleId, "window_control", String.format("{\"command\" : \"%s\"}", "" + command));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String sunRoofControl(String vehicleId, String state) {
return doCommand(vehicleId, "sun_roof_control", String.format("{\"state\" : \"%s\"}", "" + state));
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSeat(String vehicleId, int heater, int level) {
return doCommand(vehicleId, "remote_seat_heater_request", String.format("{\"heater\" : \"%s\", \"level\" : \"%s\"}", "" + heater, "" + level));
}
enum HeatSeat {
DRIVER(0),
PASSENGER(1),
REARLEFT(2),
REARCENTER(4),
REARRIGHT(5);
private final int nr;
private HeatSeat(int nr) {
this.nr = nr;
}
}
enum HeatSeatLevel {
OFF(0),
LOW(1),
MEDIUM(2),
HIGH(3);
private final int nr;
private HeatSeatLevel(int nr) {
this.nr = nr;
}
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSeat(String vehicleId, HeatSeat heatSeat, HeatSeatLevel heatSeatLevel) {
return heatSeat(vehicleId, heatSeat.nr, heatSeatLevel.nr);
}
/**
* @return null if everything is ok, or an error string if not
*/
public String heatSteeringWheel(String vehicleId, boolean state) {
return doCommand(vehicleId, "remote_steering_wheel_heater_request", String.format("{\"on\" : \"%s\"}", "" + state));
}
/*
*
*/
private String doCommand(String vehicleId, String command, String bodyContent) {
return doCommand(vehicleId, command, bodyContent, new String[] {});
}
/*
*
*/
private String doCommand(String vehicleId, String command, String bodyContent, String... okReasons) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/command/" + command)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.post(RequestBody.create(bodyContent, JsonMediaType))
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
int code = response.code();
if (!response.isSuccessful()) {
logger.warn("{}response is not succesful: {}", logPrefix, response);
return "request failed with HTTP " + code;
}
// Parse the result and build a list of vehicles
// {"response":{"result": true,,"reason": ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
responseJsonObject = responseJsonObject.get("response").getAsJsonObject();
boolean result = responseJsonObject.get("result").getAsBoolean();
String reason = responseJsonObject.get("reason").getAsString();
if (reason.equals("already_set") || Arrays.asList(okReasons).contains(reason)) {
reason = "";
}
if (!result) logger.warn(reason + ": " + request + " " + bodyContent + " " + response + " " + responseBodyContent);
if (isEmpty(reason)) {
reason = null;
}
return reason;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @return null if request had an error
*
*/
public ChargeState getChargeState(String vehicleId) {
return getState(vehicleId, "charge_state", ChargeState.class);
}
/**
* @return null if request had an error
*
*/
public ClimateState getClimateState(String vehicleId) {
return getState(vehicleId, "climate_state", ClimateState.class);
}
/**
* @return null if request had an error
*
*/
public DriveState getDriveState(String vehicleId) {
return getState(vehicleId, "drive_state", DriveState.class);
}
/**
* @return null if request had an error
*
*/
public GUISettings getGUISettings(String vehicleId) {
return getState(vehicleId, "gui_settings", GUISettings.class);
}
/**
* @return null if request had an error
*
*/
private <T> T getState(String vehicleId, String urlSuffix, Class<T> clazz) {
doTokensCheck();
try {
// Call the REST service
Request request = new Request.Builder()
.url(URL_BASE + URL_VERSION + URL_VEHICLES + vehicleId + "/data_request/" + urlSuffix)
.header(HEADER_AUTHORIZATION, authorizationHeader)
.get()
.build();
try (
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
) {
if (!response.isSuccessful()) {
logger.warn("{}response is not succesful: {}", logPrefix, response);
return null;
}
// Parse the result and build a list of vehicles
// {"response":{"gps_as_of":1565873014,"heading":71,"latitude":51.823154,"longitude":5.786151,"native_latitu ...
String responseBodyContent = responseBody.string();
JsonObject responseJsonObject = gson.fromJson(responseBodyContent, JsonObject.class);
responseJsonObject = responseJsonObject.get("response").getAsJsonObject();
return clazz.getConstructor(JsonObject.class).newInstance(responseJsonObject);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/*
*
*/
private void doTokensCheck() {
if (tokens == null) {
throw new RuntimeException("No login or setTokens was done.");
}
}
/*
*
* @param s
* @return
*/
private boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
/*
*
*/
static private void sleep(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
99244_0 | package org.akhq.utils;
import org.apache.avro.Conversions.DecimalConversion;
import org.apache.avro.Conversions.UUIDConversion;
import org.apache.avro.LogicalType;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.data.TimeConversions.*;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericFixed;
import org.apache.avro.generic.GenericRecord;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
public class AvroDeserializer {
private static final String DECIMAL = "decimal";
private static final String UUID = "uuid";
private static final String DATE = "date";
private static final String TIME_MILLIS = "time-millis";
private static final String TIME_MICROS = "time-micros";
private static final String TIMESTAMP_MILLIS = "timestamp-millis";
private static final String TIMESTAMP_MICROS = "timestamp-micros";
private static final String LOCAL_TIMESTAMP_MILLIS = "local-timestamp-millis";
private static final String LOCAL_TIMESTAMP_MICROS = "local-timestamp-micros";
private static final DecimalConversion DECIMAL_CONVERSION = new DecimalConversion();
private static final UUIDConversion UUID_CONVERSION = new UUIDConversion();
private static final DateConversion DATE_CONVERSION = new DateConversion();
private static final TimeMicrosConversion TIME_MICROS_CONVERSION = new TimeMicrosConversion();
private static final TimeMillisConversion TIME_MILLIS_CONVERSION = new TimeMillisConversion();
private static final TimestampMicrosConversion TIMESTAMP_MICROS_CONVERSION = new TimestampMicrosConversion();
private static final TimestampMillisConversion TIMESTAMP_MILLIS_CONVERSION = new TimestampMillisConversion();
private static final LocalTimestampMicrosConversion LOCAL_TIMESTAMP_MICROS_CONVERSION = new LocalTimestampMicrosConversion();
private static final LocalTimestampMillisConversion LOCAL_TIMESTAMP_MILLIS_CONVERSION = new LocalTimestampMillisConversion();
public static Map<String, Object> recordDeserializer(GenericRecord record) {
return record
.getSchema()
.getFields()
.stream()
.collect(
LinkedHashMap::new, // preserve schema field order
(m, v) -> m.put(
v.name(),
AvroDeserializer.objectDeserializer(record.get(v.name()), v.schema())
),
HashMap::putAll
);
}
@SuppressWarnings("unchecked")
private static Object objectDeserializer(Object value, Schema schema) {
LogicalType logicalType = schema.getLogicalType();
Type primitiveType = schema.getType();
if (logicalType != null) {
switch (logicalType.getName()) {
case DATE:
return AvroDeserializer.dateDeserializer(value, schema, primitiveType, logicalType);
case DECIMAL:
return AvroDeserializer.decimalDeserializer(value, schema, primitiveType, logicalType);
case TIME_MICROS:
return AvroDeserializer.timeMicrosDeserializer(value, schema, primitiveType, logicalType);
case TIME_MILLIS:
return AvroDeserializer.timeMillisDeserializer(value, schema, primitiveType, logicalType);
case TIMESTAMP_MICROS:
return AvroDeserializer.timestampMicrosDeserializer(value, schema, primitiveType, logicalType);
case TIMESTAMP_MILLIS:
return AvroDeserializer.timestampMillisDeserializer(value, schema, primitiveType, logicalType);
case LOCAL_TIMESTAMP_MICROS:
return AvroDeserializer.localTimestampMicrosDeserializer(value, schema, primitiveType, logicalType);
case LOCAL_TIMESTAMP_MILLIS:
return AvroDeserializer.localTimestampMillisDeserializer(value, schema, primitiveType, logicalType);
case UUID:
return AvroDeserializer.uuidDeserializer(value, schema, primitiveType, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + logicalType);
}
} else {
switch (primitiveType) {
case UNION:
return AvroDeserializer.unionDeserializer(value, schema);
case MAP:
return AvroDeserializer.mapDeserializer((Map<String, ?>) value, schema);
case RECORD:
return AvroDeserializer.recordDeserializer((GenericRecord) value);
case ENUM:
return value.toString();
case ARRAY:
return arrayDeserializer((Collection<?>) value, schema);
case FIXED:
return ((GenericFixed) value).bytes();
case STRING:
return ((CharSequence) value).toString();
case BYTES:
return ((ByteBuffer) value).array();
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case BOOLEAN:
case NULL:
return value;
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
}
private static Object unionDeserializer(Object value, Schema schema) {
return AvroDeserializer.objectDeserializer(value, schema
.getTypes()
.stream()
.filter(type -> {
try {
return new GenericData().validate(type, value);
} catch (Exception e) {
return false;
}
})
.findFirst()
.orElseThrow());
}
private static Map<String, ?> mapDeserializer(Map<String, ?> value, Schema schema) {
return value
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> AvroDeserializer.objectDeserializer(e.getValue(), schema.getValueType()))
);
}
private static Collection<?> arrayDeserializer(Collection<?> value, Schema schema) {
return value
.stream()
.map(e -> AvroDeserializer.objectDeserializer(e, schema.getElementType()))
.collect(Collectors.toList());
}
private static Instant timestampMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case LONG:
return AvroDeserializer.TIMESTAMP_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
private static Instant timestampMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.TIMESTAMP_MILLIS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalDateTime localTimestampMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case LONG:
return AvroDeserializer.LOCAL_TIMESTAMP_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
private static LocalDateTime localTimestampMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.LOCAL_TIMESTAMP_MILLIS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalTime timeMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.TIME_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalTime timeMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.INT) {
return AvroDeserializer.TIME_MILLIS_CONVERSION.fromInt((Integer) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalDate dateDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.INT) {
return AvroDeserializer.DATE_CONVERSION.fromInt((Integer) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static UUID uuidDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.STRING) {
return AvroDeserializer.UUID_CONVERSION.fromCharSequence((CharSequence) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static BigDecimal decimalDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case BYTES:
return AvroDeserializer.DECIMAL_CONVERSION.fromBytes((ByteBuffer) value, schema, logicalType);
case FIXED:
return AvroDeserializer.DECIMAL_CONVERSION.fromFixed((GenericFixed) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
}
| tchiotludo/akhq | src/main/java/org/akhq/utils/AvroDeserializer.java | 2,783 | // preserve schema field order | line_comment | nl | package org.akhq.utils;
import org.apache.avro.Conversions.DecimalConversion;
import org.apache.avro.Conversions.UUIDConversion;
import org.apache.avro.LogicalType;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.data.TimeConversions.*;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericFixed;
import org.apache.avro.generic.GenericRecord;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
public class AvroDeserializer {
private static final String DECIMAL = "decimal";
private static final String UUID = "uuid";
private static final String DATE = "date";
private static final String TIME_MILLIS = "time-millis";
private static final String TIME_MICROS = "time-micros";
private static final String TIMESTAMP_MILLIS = "timestamp-millis";
private static final String TIMESTAMP_MICROS = "timestamp-micros";
private static final String LOCAL_TIMESTAMP_MILLIS = "local-timestamp-millis";
private static final String LOCAL_TIMESTAMP_MICROS = "local-timestamp-micros";
private static final DecimalConversion DECIMAL_CONVERSION = new DecimalConversion();
private static final UUIDConversion UUID_CONVERSION = new UUIDConversion();
private static final DateConversion DATE_CONVERSION = new DateConversion();
private static final TimeMicrosConversion TIME_MICROS_CONVERSION = new TimeMicrosConversion();
private static final TimeMillisConversion TIME_MILLIS_CONVERSION = new TimeMillisConversion();
private static final TimestampMicrosConversion TIMESTAMP_MICROS_CONVERSION = new TimestampMicrosConversion();
private static final TimestampMillisConversion TIMESTAMP_MILLIS_CONVERSION = new TimestampMillisConversion();
private static final LocalTimestampMicrosConversion LOCAL_TIMESTAMP_MICROS_CONVERSION = new LocalTimestampMicrosConversion();
private static final LocalTimestampMillisConversion LOCAL_TIMESTAMP_MILLIS_CONVERSION = new LocalTimestampMillisConversion();
public static Map<String, Object> recordDeserializer(GenericRecord record) {
return record
.getSchema()
.getFields()
.stream()
.collect(
LinkedHashMap::new, // preserve schema<SUF>
(m, v) -> m.put(
v.name(),
AvroDeserializer.objectDeserializer(record.get(v.name()), v.schema())
),
HashMap::putAll
);
}
@SuppressWarnings("unchecked")
private static Object objectDeserializer(Object value, Schema schema) {
LogicalType logicalType = schema.getLogicalType();
Type primitiveType = schema.getType();
if (logicalType != null) {
switch (logicalType.getName()) {
case DATE:
return AvroDeserializer.dateDeserializer(value, schema, primitiveType, logicalType);
case DECIMAL:
return AvroDeserializer.decimalDeserializer(value, schema, primitiveType, logicalType);
case TIME_MICROS:
return AvroDeserializer.timeMicrosDeserializer(value, schema, primitiveType, logicalType);
case TIME_MILLIS:
return AvroDeserializer.timeMillisDeserializer(value, schema, primitiveType, logicalType);
case TIMESTAMP_MICROS:
return AvroDeserializer.timestampMicrosDeserializer(value, schema, primitiveType, logicalType);
case TIMESTAMP_MILLIS:
return AvroDeserializer.timestampMillisDeserializer(value, schema, primitiveType, logicalType);
case LOCAL_TIMESTAMP_MICROS:
return AvroDeserializer.localTimestampMicrosDeserializer(value, schema, primitiveType, logicalType);
case LOCAL_TIMESTAMP_MILLIS:
return AvroDeserializer.localTimestampMillisDeserializer(value, schema, primitiveType, logicalType);
case UUID:
return AvroDeserializer.uuidDeserializer(value, schema, primitiveType, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + logicalType);
}
} else {
switch (primitiveType) {
case UNION:
return AvroDeserializer.unionDeserializer(value, schema);
case MAP:
return AvroDeserializer.mapDeserializer((Map<String, ?>) value, schema);
case RECORD:
return AvroDeserializer.recordDeserializer((GenericRecord) value);
case ENUM:
return value.toString();
case ARRAY:
return arrayDeserializer((Collection<?>) value, schema);
case FIXED:
return ((GenericFixed) value).bytes();
case STRING:
return ((CharSequence) value).toString();
case BYTES:
return ((ByteBuffer) value).array();
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case BOOLEAN:
case NULL:
return value;
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
}
private static Object unionDeserializer(Object value, Schema schema) {
return AvroDeserializer.objectDeserializer(value, schema
.getTypes()
.stream()
.filter(type -> {
try {
return new GenericData().validate(type, value);
} catch (Exception e) {
return false;
}
})
.findFirst()
.orElseThrow());
}
private static Map<String, ?> mapDeserializer(Map<String, ?> value, Schema schema) {
return value
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> AvroDeserializer.objectDeserializer(e.getValue(), schema.getValueType()))
);
}
private static Collection<?> arrayDeserializer(Collection<?> value, Schema schema) {
return value
.stream()
.map(e -> AvroDeserializer.objectDeserializer(e, schema.getElementType()))
.collect(Collectors.toList());
}
private static Instant timestampMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case LONG:
return AvroDeserializer.TIMESTAMP_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
private static Instant timestampMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.TIMESTAMP_MILLIS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalDateTime localTimestampMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case LONG:
return AvroDeserializer.LOCAL_TIMESTAMP_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
private static LocalDateTime localTimestampMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.LOCAL_TIMESTAMP_MILLIS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalTime timeMicrosDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.LONG) {
return AvroDeserializer.TIME_MICROS_CONVERSION.fromLong((Long) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalTime timeMillisDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.INT) {
return AvroDeserializer.TIME_MILLIS_CONVERSION.fromInt((Integer) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static LocalDate dateDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.INT) {
return AvroDeserializer.DATE_CONVERSION.fromInt((Integer) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static UUID uuidDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
if (primitiveType == Type.STRING) {
return AvroDeserializer.UUID_CONVERSION.fromCharSequence((CharSequence) value, schema, logicalType);
}
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
private static BigDecimal decimalDeserializer(Object value, Schema schema, Type primitiveType, LogicalType logicalType) {
switch (primitiveType) {
case BYTES:
return AvroDeserializer.DECIMAL_CONVERSION.fromBytes((ByteBuffer) value, schema, logicalType);
case FIXED:
return AvroDeserializer.DECIMAL_CONVERSION.fromFixed((GenericFixed) value, schema, logicalType);
default:
throw new IllegalStateException("Unexpected value: " + primitiveType);
}
}
}
|
79565_0 | package avd.proftaak.rentmycar.controllers;
import avd.proftaak.rentmycar.controllers.dto.Order;
import avd.proftaak.rentmycar.domain.RentalService;
import avd.proftaak.rentmycar.domain.User;
import avd.proftaak.rentmycar.repository.UserRepository;
import avd.proftaak.rentmycar.services.CarService;
import lombok.extern.slf4j.Slf4j;
import avd.proftaak.rentmycar.domain.Car;
import avd.proftaak.rentmycar.repository.CarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
//Carcontroller doet post en get mappings correct. Delete mappings hebik nog niet geprobeerd maar dat kan ik zelf wel doen
@Slf4j
@RestController
@RequestMapping("/cars")
public class CarController {
private final CarRepository carRepository;
private final UserRepository userRepository;
private final CarService carService;
@Autowired
public CarController(CarRepository carRepository, UserRepository userRepository, CarService carService) {
this.carRepository = carRepository;
this.userRepository = userRepository;
this.carService = carService;
}
//Gets all cars based on the model
@GetMapping
public ResponseEntity<List<Car>> getAll(
@RequestParam(required = false) Integer maxKilometers,
@RequestParam(required = false) Double maxCost)
{
List<Car> found = new ArrayList<>();
found.addAll(carRepository.customFindCars(maxKilometers, maxCost));
return ResponseEntity.ok(found);
}
//Gets a car by its id
@GetMapping("/{carId}")
public Optional<Car> getById(@PathVariable Long carId){
return carRepository.findById(carId);
}
//Creates new car
@PostMapping
public ResponseEntity<Car> create(@RequestBody Car newCar){
try{
Car car = carRepository.save(newCar);
return new ResponseEntity<>(car, HttpStatus.CREATED);
}catch (IllegalArgumentException e){
log.info("Error creating new car " + newCar + e.getMessage());
return ResponseEntity.badRequest().build();
}
}
//Deletes car based on id
@DeleteMapping
public ResponseEntity<HttpStatus> deleteById(@PathVariable Long carId){
if(!carRepository.existsById(carId)){
return ResponseEntity.notFound().build();
}
carRepository.deleteById(carId);
return ResponseEntity.ok().build();
}
} | tcudjoe/AVD-RentMyCar | RentMyCarApi/src/main/java/avd/proftaak/rentmycar/controllers/CarController.java | 748 | //Carcontroller doet post en get mappings correct. Delete mappings hebik nog niet geprobeerd maar dat kan ik zelf wel doen | line_comment | nl | package avd.proftaak.rentmycar.controllers;
import avd.proftaak.rentmycar.controllers.dto.Order;
import avd.proftaak.rentmycar.domain.RentalService;
import avd.proftaak.rentmycar.domain.User;
import avd.proftaak.rentmycar.repository.UserRepository;
import avd.proftaak.rentmycar.services.CarService;
import lombok.extern.slf4j.Slf4j;
import avd.proftaak.rentmycar.domain.Car;
import avd.proftaak.rentmycar.repository.CarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
//Carcontroller doet<SUF>
@Slf4j
@RestController
@RequestMapping("/cars")
public class CarController {
private final CarRepository carRepository;
private final UserRepository userRepository;
private final CarService carService;
@Autowired
public CarController(CarRepository carRepository, UserRepository userRepository, CarService carService) {
this.carRepository = carRepository;
this.userRepository = userRepository;
this.carService = carService;
}
//Gets all cars based on the model
@GetMapping
public ResponseEntity<List<Car>> getAll(
@RequestParam(required = false) Integer maxKilometers,
@RequestParam(required = false) Double maxCost)
{
List<Car> found = new ArrayList<>();
found.addAll(carRepository.customFindCars(maxKilometers, maxCost));
return ResponseEntity.ok(found);
}
//Gets a car by its id
@GetMapping("/{carId}")
public Optional<Car> getById(@PathVariable Long carId){
return carRepository.findById(carId);
}
//Creates new car
@PostMapping
public ResponseEntity<Car> create(@RequestBody Car newCar){
try{
Car car = carRepository.save(newCar);
return new ResponseEntity<>(car, HttpStatus.CREATED);
}catch (IllegalArgumentException e){
log.info("Error creating new car " + newCar + e.getMessage());
return ResponseEntity.badRequest().build();
}
}
//Deletes car based on id
@DeleteMapping
public ResponseEntity<HttpStatus> deleteById(@PathVariable Long carId){
if(!carRepository.existsById(carId)){
return ResponseEntity.notFound().build();
}
carRepository.deleteById(carId);
return ResponseEntity.ok().build();
}
} |
100510_30 | package com.ducbase.knxplatform.adapters;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.xml.bind.JAXBException;
import org.jivesoftware.smack.XMPPException;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.management.ManagementService;
import tuwien.auto.calimero.CloseEvent;
import tuwien.auto.calimero.FrameEvent;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.datapoint.Datapoint;
import tuwien.auto.calimero.datapoint.StateDP;
import tuwien.auto.calimero.dptxlator.DPT;
import tuwien.auto.calimero.exception.KNXException;
import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.exception.KNXTimeoutException;
import tuwien.auto.calimero.knxnetip.KNXnetIPConnection;
import tuwien.auto.calimero.link.KNXLinkClosedException;
import tuwien.auto.calimero.link.KNXNetworkLink;
import tuwien.auto.calimero.link.KNXNetworkLinkIP;
import tuwien.auto.calimero.link.event.NetworkLinkListener;
import tuwien.auto.calimero.link.medium.TPSettings;
import tuwien.auto.calimero.process.ProcessCommunicator;
import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
import com.ducbase.knxplatform.WebSocketManager;
import com.ducbase.knxplatform.adapters.devices.KNXDimmedLight;
import com.ducbase.knxplatform.adapters.devices.KNXShutter;
import com.ducbase.knxplatform.adapters.devices.KNXSwitched;
import com.ducbase.knxplatform.adapters.devices.KNXTemperatureSensor;
import com.ducbase.knxplatform.adapters.devices.KNXThermostat;
import com.ducbase.knxplatform.connectors.GoogleTalkConnector;
import com.ducbase.knxplatform.devices.Device;
import com.ducbase.knxplatform.devices.DeviceManager;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
/**
* abstraction layer for the KNX interface.
*
* This class will:
* <li>keep a map of all KNX devices to manage/monitor</li>
* <li>keep a map of group addresses and the device properties they map to</li>
*
*
* @author [email protected]
*
*/
public class KNXAdapter {
static Logger logger = Logger.getLogger(KNXAdapter.class.getName());
private KNXNetworkLink link;
private ProcessCommunicator pc;
private KNXProcessListener listener;
private static final String CACHE_NAME = "distributed-knx-cache"; // correspond with name in ehcache.xml.
Map<String, String> listenFor = new HashMap<String, String>(); // datapoint - device id
Map<String, DPT> typeMap = new HashMap<String, DPT>();
private Date lastConnected;
/**
* a KNXAdapter maintains a cache of group address states. Mainly for those group addresses used for Device state's.
*/
private Cache cache;
private static KNXAdapter instance;
/**
* Create a KNXAdapter
*
* TODO: make singleton
*/
private KNXAdapter() {
logger.info("Creating KNX Adapter");
// Adding listener
listener = new KNXProcessListener(this);
// start cache
logger.fine("Creating cache");
CacheManager cacheMgr = CacheManager.create();
// Register cache manager as mBean!
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheMgr, mBeanServer, false, false, false, true);
cache = cacheMgr.getCache(CACHE_NAME);
}
public static KNXAdapter getInstance() {
if (instance == null) {
synchronized(KNXAdapter.class) {
if (instance == null) {
instance = new KNXAdapter();
}
}
}
return instance;
}
/**
* prefetch state from KNX. This method will send out read requests for all known devices.
* The responses will preload the cache.
*
* TODO This is a hacked up version. This should load from a list of configured devices.
*
*/
public void prefetch() {
Runnable task = new Runnable() {
final int MAX_RETRIES = 5;
boolean hasRun = false;
int retries = 0;
@Override
public void run() {
while (!hasRun) {
if (retries > MAX_RETRIES) {
logger.warning("Retries exceeded. Not retrying to prefetch.");
return;
} else {
retries++;
}
try {
Thread.sleep(20 * 1000); // wait 20 secs before starting to give us time to boot
} catch (InterruptedException e1) {}
if (pc == null) {
logger.warning("Can't prefetch. Not (yet?) connected!");
continue;
}
logger.info("Prefetching states from KNX (in a separate thread)");
StringBuffer prefetchList = new StringBuffer();
for(String address: listenFor.keySet()) {
prefetchList.append(address + " ");
try {
GroupAddress ga = new GroupAddress(address);
DPT dpt = typeMap.get(address);
Datapoint dp = new StateDP(ga, "", 0, dpt.getID());
pc.read(dp);
} catch (KNXException e) {
logger.warning("Exception while prefetching " + address + " - " + e.getMessage());
}
try {
Thread.sleep(250); // wait a bit before starting the next... don't overload KNX.
} catch (InterruptedException e1) {}
}
logger.info("Done prefetching.");
logger.fine("Prefetch list: " + prefetchList);
hasRun = true;
}
}
};
Thread thread = new Thread(task);
thread.start();
}
/**
* check adapter connection to KNX. More specifically, it checks the <code>KNXNetworkLinkIP</code> health.
* If not connected, this method does some cleanup too.
*
* @return a <code>boolean</code> to indicate adapter health.
*/
public boolean isOk() {
if (link == null) {
logger.warning("KNX Link is null");
if (pc != null) {
pc.detach();
}
return false;
}
if (!link.isOpen()) {
logger.warning("KNX Link not open");
if (pc != null) {
pc.detach();
}
link.close();
return false;
}
logger.fine("Link is OK!");
return true;
}
public String getLastConnect() {
if (this.lastConnected == null) {
return "";
}
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss");
String retVal = formatter.format(this.lastConnected);
return retVal;
}
public synchronized void connect() {
logger.fine("Connecting to KNX");
// find own IP address
InetAddress localAddress = null;
try {
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
if (addrs != null && logger.isLoggable(Level.FINE)) { // only run this if logging fine.
String msg = "Hostname: " + hostName + ", got " + addrs.length + " address(es)";
for (InetAddress a: addrs) {
msg += " - " + a.getHostAddress();
}
logger.fine(msg);
}
for(InetAddress addr: addrs) {
// TODO: hardcoding to my subnet, change to more flexible mechanism later.
//if( !addr.isLoopbackAddress() && addr.isSiteLocalAddress() ) {
if (addr.getHostAddress().startsWith("192.168.2.")) {
logger.fine("IP Address found: " + addr.getHostAddress());
localAddress = addr;
}
}
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
logger.info("Using ip address: " + localAddress.getHostAddress());
if (link != null) { // cleanup in case we've been here before.
link.close();
}
// connect to KNX
try {
link = new KNXNetworkLinkIP(
KNXNetworkLinkIP.TUNNEL,
new InetSocketAddress(localAddress, 0),
new InetSocketAddress(InetAddress.getByName("192.168.2.150"), KNXnetIPConnection.IP_PORT),
false, // don't use NAT
TPSettings.TP1); // select TP1
link.addLinkListener(new NetworkLinkListener() {
@Override
public void linkClosed(CloseEvent e) {
if (!e.isUserRequest()) {
logger.warning("Link closed! Let's reconnect. (" + e.getReason() + " | " + e.getSource().toString() + ")");
try {Thread.sleep(5 * 1000); } catch (Exception ex) {}; // wait 5 seconds to avoid frantic reconnect.
connect();
return;
}
if (!link.isOpen()) {
logger.severe("KNX Link lost!");
}
logger.severe("Through the cracks: " + e.getSource());
}
@Override
public void indication(FrameEvent e) {
// logger.fine("INDICATION: " + e.toString());
}
@Override
public void confirmation(FrameEvent e) {
// logger.fine("CONFIRMATION: " + e.toString());
}
});
if (pc != null) {
pc.removeProcessListener(listener);
pc.detach();
}
pc = new ProcessCommunicatorImpl(link);
pc.setResponseTimeout(2); // TODO - make configurable?
if (listener != null) {
pc.addProcessListener(listener);
}
} catch (KNXException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
// set state
this.lastConnected = new Date();
}
public void disconnect() {
logger.info("Disconnecting from KNX");
if (pc != null) {
pc.removeProcessListener(listener);
pc.detach();
}
if (link != null) {
link.close();
link = null;
}
}
/**
* add KNX group address updates to cache
*
* @param groupAddress a String object representing the group address
* @param value the String value of the group addresss
* @param dpt the DPT object, describing the type of the group address
*/
@Deprecated
public void deviceUpdate(String groupAddress, String value, DPT dpt) {
logger.fine("Updating cache for " + groupAddress);
Element valueElement = new Element(groupAddress, value);
cache.put(valueElement);
//TODO: no need to save DPT... we'll use device definition for that.
// Use tuwien.auto.calimero.dptxlator.TranslatorTypes is needed
// btw: is dpt.getID() enough? Does it include the mainType of the DPT?
Element typeElement = new Element(groupAddress + "_dpt", dpt.getID());
cache.put(typeElement);
}
public void updateDevice(String groupAddress, String value) {
logger.fine("Updating cache for " + groupAddress);
Element valueElement = new Element(groupAddress, value);
cache.put(valueElement);
// find device from group ID (look in listenFor)
String deviceId = listenFor.get(groupAddress);
DeviceManager deviceManager = DeviceManager.getInstance();
Device device = deviceManager.getDevice(deviceId);
// TODO - this should change in Events and subscribing to Events!
// B2 - Woning volledig
// B3 - Woning gedeeltelijk
// 0/1/3 - Brand
// 0/1/4 - Alarm
try {
if (device.getId().equals("B2")) {
boolean on = ((KNXSwitched) device).isOn();
GoogleTalkConnector.getInstance().sendMessage("Alarm " + (on ? "on":"off"));
}
// Let's not send chat messages for partial alarm... annoying!
// if (device.getId().equals("B3")) {
// boolean on = ((KNXSwitched) device).isOn();
// GoogleTalkConnector.getInstance().sendMessage("Alarm (partial) " + (on ? "on":"off"));
// }
} catch (XMPPException | IOException e) {
logger.severe("Unable to send message: " + e.getMessage());
}
// END TODO
// device -> JSON
Class[] classes = new Class[] {KNXSwitched.class, KNXDimmedLight.class, KNXTemperatureSensor.class, KNXThermostat.class, KNXShutter.class};
try {
JSONJAXBContext context = new JSONJAXBContext(classes);
JSONMarshaller m = context.createJSONMarshaller();
StringWriter writer = new StringWriter();
m.marshallToJSON(device, writer);
String json = writer.toString();
logger.fine("JSON: " + json);
WebSocketManager wsMgr = WebSocketManager.getInstance();
wsMgr.broadcast(json);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendBoolean(String groupAddress, boolean value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
pc.write(address, value);
} catch (KNXLinkClosedException | KNXFormatException | KNXTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendIntUnscaled(String groupAddress, int value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value, ProcessCommunicator.UNSCALED);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendIntScaled(String groupAddress, int value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value, ProcessCommunicator.SCALING);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendFloat(String groupAddress, float value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* TODO remove this method... temporary one.
* @param groupAddress
* @return
*/
public String getValueForGroupAddress(String groupAddress) {
Element valueEl = cache.get(groupAddress);
if (valueEl == null) return "";
return (String) valueEl.getValue();
}
/**
* Register datapoints to listen for on the KNX bus, for device with id.
*
* @param listenGroups
* @param id
*/
public void registerListenFor(String[] listenGroups, String id) {
for(String dp: listenGroups) {
this.listenFor.put(dp, id);
}
}
public void addTypeMap(Map<String, DPT> typeMap) {
this.typeMap.putAll(typeMap);
}
}
| tdeckers/knx-platform | src/com/ducbase/knxplatform/adapters/KNXAdapter.java | 4,894 | // B3 - Woning gedeeltelijk
| line_comment | nl | package com.ducbase.knxplatform.adapters;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.xml.bind.JAXBException;
import org.jivesoftware.smack.XMPPException;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.management.ManagementService;
import tuwien.auto.calimero.CloseEvent;
import tuwien.auto.calimero.FrameEvent;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.datapoint.Datapoint;
import tuwien.auto.calimero.datapoint.StateDP;
import tuwien.auto.calimero.dptxlator.DPT;
import tuwien.auto.calimero.exception.KNXException;
import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.exception.KNXTimeoutException;
import tuwien.auto.calimero.knxnetip.KNXnetIPConnection;
import tuwien.auto.calimero.link.KNXLinkClosedException;
import tuwien.auto.calimero.link.KNXNetworkLink;
import tuwien.auto.calimero.link.KNXNetworkLinkIP;
import tuwien.auto.calimero.link.event.NetworkLinkListener;
import tuwien.auto.calimero.link.medium.TPSettings;
import tuwien.auto.calimero.process.ProcessCommunicator;
import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
import com.ducbase.knxplatform.WebSocketManager;
import com.ducbase.knxplatform.adapters.devices.KNXDimmedLight;
import com.ducbase.knxplatform.adapters.devices.KNXShutter;
import com.ducbase.knxplatform.adapters.devices.KNXSwitched;
import com.ducbase.knxplatform.adapters.devices.KNXTemperatureSensor;
import com.ducbase.knxplatform.adapters.devices.KNXThermostat;
import com.ducbase.knxplatform.connectors.GoogleTalkConnector;
import com.ducbase.knxplatform.devices.Device;
import com.ducbase.knxplatform.devices.DeviceManager;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
/**
* abstraction layer for the KNX interface.
*
* This class will:
* <li>keep a map of all KNX devices to manage/monitor</li>
* <li>keep a map of group addresses and the device properties they map to</li>
*
*
* @author [email protected]
*
*/
public class KNXAdapter {
static Logger logger = Logger.getLogger(KNXAdapter.class.getName());
private KNXNetworkLink link;
private ProcessCommunicator pc;
private KNXProcessListener listener;
private static final String CACHE_NAME = "distributed-knx-cache"; // correspond with name in ehcache.xml.
Map<String, String> listenFor = new HashMap<String, String>(); // datapoint - device id
Map<String, DPT> typeMap = new HashMap<String, DPT>();
private Date lastConnected;
/**
* a KNXAdapter maintains a cache of group address states. Mainly for those group addresses used for Device state's.
*/
private Cache cache;
private static KNXAdapter instance;
/**
* Create a KNXAdapter
*
* TODO: make singleton
*/
private KNXAdapter() {
logger.info("Creating KNX Adapter");
// Adding listener
listener = new KNXProcessListener(this);
// start cache
logger.fine("Creating cache");
CacheManager cacheMgr = CacheManager.create();
// Register cache manager as mBean!
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheMgr, mBeanServer, false, false, false, true);
cache = cacheMgr.getCache(CACHE_NAME);
}
public static KNXAdapter getInstance() {
if (instance == null) {
synchronized(KNXAdapter.class) {
if (instance == null) {
instance = new KNXAdapter();
}
}
}
return instance;
}
/**
* prefetch state from KNX. This method will send out read requests for all known devices.
* The responses will preload the cache.
*
* TODO This is a hacked up version. This should load from a list of configured devices.
*
*/
public void prefetch() {
Runnable task = new Runnable() {
final int MAX_RETRIES = 5;
boolean hasRun = false;
int retries = 0;
@Override
public void run() {
while (!hasRun) {
if (retries > MAX_RETRIES) {
logger.warning("Retries exceeded. Not retrying to prefetch.");
return;
} else {
retries++;
}
try {
Thread.sleep(20 * 1000); // wait 20 secs before starting to give us time to boot
} catch (InterruptedException e1) {}
if (pc == null) {
logger.warning("Can't prefetch. Not (yet?) connected!");
continue;
}
logger.info("Prefetching states from KNX (in a separate thread)");
StringBuffer prefetchList = new StringBuffer();
for(String address: listenFor.keySet()) {
prefetchList.append(address + " ");
try {
GroupAddress ga = new GroupAddress(address);
DPT dpt = typeMap.get(address);
Datapoint dp = new StateDP(ga, "", 0, dpt.getID());
pc.read(dp);
} catch (KNXException e) {
logger.warning("Exception while prefetching " + address + " - " + e.getMessage());
}
try {
Thread.sleep(250); // wait a bit before starting the next... don't overload KNX.
} catch (InterruptedException e1) {}
}
logger.info("Done prefetching.");
logger.fine("Prefetch list: " + prefetchList);
hasRun = true;
}
}
};
Thread thread = new Thread(task);
thread.start();
}
/**
* check adapter connection to KNX. More specifically, it checks the <code>KNXNetworkLinkIP</code> health.
* If not connected, this method does some cleanup too.
*
* @return a <code>boolean</code> to indicate adapter health.
*/
public boolean isOk() {
if (link == null) {
logger.warning("KNX Link is null");
if (pc != null) {
pc.detach();
}
return false;
}
if (!link.isOpen()) {
logger.warning("KNX Link not open");
if (pc != null) {
pc.detach();
}
link.close();
return false;
}
logger.fine("Link is OK!");
return true;
}
public String getLastConnect() {
if (this.lastConnected == null) {
return "";
}
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss");
String retVal = formatter.format(this.lastConnected);
return retVal;
}
public synchronized void connect() {
logger.fine("Connecting to KNX");
// find own IP address
InetAddress localAddress = null;
try {
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
if (addrs != null && logger.isLoggable(Level.FINE)) { // only run this if logging fine.
String msg = "Hostname: " + hostName + ", got " + addrs.length + " address(es)";
for (InetAddress a: addrs) {
msg += " - " + a.getHostAddress();
}
logger.fine(msg);
}
for(InetAddress addr: addrs) {
// TODO: hardcoding to my subnet, change to more flexible mechanism later.
//if( !addr.isLoopbackAddress() && addr.isSiteLocalAddress() ) {
if (addr.getHostAddress().startsWith("192.168.2.")) {
logger.fine("IP Address found: " + addr.getHostAddress());
localAddress = addr;
}
}
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
logger.info("Using ip address: " + localAddress.getHostAddress());
if (link != null) { // cleanup in case we've been here before.
link.close();
}
// connect to KNX
try {
link = new KNXNetworkLinkIP(
KNXNetworkLinkIP.TUNNEL,
new InetSocketAddress(localAddress, 0),
new InetSocketAddress(InetAddress.getByName("192.168.2.150"), KNXnetIPConnection.IP_PORT),
false, // don't use NAT
TPSettings.TP1); // select TP1
link.addLinkListener(new NetworkLinkListener() {
@Override
public void linkClosed(CloseEvent e) {
if (!e.isUserRequest()) {
logger.warning("Link closed! Let's reconnect. (" + e.getReason() + " | " + e.getSource().toString() + ")");
try {Thread.sleep(5 * 1000); } catch (Exception ex) {}; // wait 5 seconds to avoid frantic reconnect.
connect();
return;
}
if (!link.isOpen()) {
logger.severe("KNX Link lost!");
}
logger.severe("Through the cracks: " + e.getSource());
}
@Override
public void indication(FrameEvent e) {
// logger.fine("INDICATION: " + e.toString());
}
@Override
public void confirmation(FrameEvent e) {
// logger.fine("CONFIRMATION: " + e.toString());
}
});
if (pc != null) {
pc.removeProcessListener(listener);
pc.detach();
}
pc = new ProcessCommunicatorImpl(link);
pc.setResponseTimeout(2); // TODO - make configurable?
if (listener != null) {
pc.addProcessListener(listener);
}
} catch (KNXException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
// set state
this.lastConnected = new Date();
}
public void disconnect() {
logger.info("Disconnecting from KNX");
if (pc != null) {
pc.removeProcessListener(listener);
pc.detach();
}
if (link != null) {
link.close();
link = null;
}
}
/**
* add KNX group address updates to cache
*
* @param groupAddress a String object representing the group address
* @param value the String value of the group addresss
* @param dpt the DPT object, describing the type of the group address
*/
@Deprecated
public void deviceUpdate(String groupAddress, String value, DPT dpt) {
logger.fine("Updating cache for " + groupAddress);
Element valueElement = new Element(groupAddress, value);
cache.put(valueElement);
//TODO: no need to save DPT... we'll use device definition for that.
// Use tuwien.auto.calimero.dptxlator.TranslatorTypes is needed
// btw: is dpt.getID() enough? Does it include the mainType of the DPT?
Element typeElement = new Element(groupAddress + "_dpt", dpt.getID());
cache.put(typeElement);
}
public void updateDevice(String groupAddress, String value) {
logger.fine("Updating cache for " + groupAddress);
Element valueElement = new Element(groupAddress, value);
cache.put(valueElement);
// find device from group ID (look in listenFor)
String deviceId = listenFor.get(groupAddress);
DeviceManager deviceManager = DeviceManager.getInstance();
Device device = deviceManager.getDevice(deviceId);
// TODO - this should change in Events and subscribing to Events!
// B2 - Woning volledig
// B3 -<SUF>
// 0/1/3 - Brand
// 0/1/4 - Alarm
try {
if (device.getId().equals("B2")) {
boolean on = ((KNXSwitched) device).isOn();
GoogleTalkConnector.getInstance().sendMessage("Alarm " + (on ? "on":"off"));
}
// Let's not send chat messages for partial alarm... annoying!
// if (device.getId().equals("B3")) {
// boolean on = ((KNXSwitched) device).isOn();
// GoogleTalkConnector.getInstance().sendMessage("Alarm (partial) " + (on ? "on":"off"));
// }
} catch (XMPPException | IOException e) {
logger.severe("Unable to send message: " + e.getMessage());
}
// END TODO
// device -> JSON
Class[] classes = new Class[] {KNXSwitched.class, KNXDimmedLight.class, KNXTemperatureSensor.class, KNXThermostat.class, KNXShutter.class};
try {
JSONJAXBContext context = new JSONJAXBContext(classes);
JSONMarshaller m = context.createJSONMarshaller();
StringWriter writer = new StringWriter();
m.marshallToJSON(device, writer);
String json = writer.toString();
logger.fine("JSON: " + json);
WebSocketManager wsMgr = WebSocketManager.getInstance();
wsMgr.broadcast(json);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendBoolean(String groupAddress, boolean value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
pc.write(address, value);
} catch (KNXLinkClosedException | KNXFormatException | KNXTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendIntUnscaled(String groupAddress, int value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value, ProcessCommunicator.UNSCALED);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendIntScaled(String groupAddress, int value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value, ProcessCommunicator.SCALING);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendFloat(String groupAddress, float value) {
try {
GroupAddress address = new GroupAddress(groupAddress);
logger.fine("About to send...");
pc.write(address, value);
logger.fine("Sent.");
} catch (KNXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* TODO remove this method... temporary one.
* @param groupAddress
* @return
*/
public String getValueForGroupAddress(String groupAddress) {
Element valueEl = cache.get(groupAddress);
if (valueEl == null) return "";
return (String) valueEl.getValue();
}
/**
* Register datapoints to listen for on the KNX bus, for device with id.
*
* @param listenGroups
* @param id
*/
public void registerListenFor(String[] listenGroups, String id) {
for(String dp: listenGroups) {
this.listenFor.put(dp, id);
}
}
public void addTypeMap(Map<String, DPT> typeMap) {
this.typeMap.putAll(typeMap);
}
}
|
8258_29 | /**
* **********************************************************************
*
* <p>DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* <p>Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* <p>Use is subject to license terms.
*
* <p>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. You can also obtain a copy of the License at
* http://odftoolkit.org/docs/license.txt
*
* <p>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.
*
* <p>See the License for the specific language governing permissions and limitations under the
* License.
*
* <p>**********************************************************************
*/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.element.table;
import org.odftoolkit.odfdom.dom.DefaultElementVisitor;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeBooleanValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeCurrencyAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeDateValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeStringValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeTimeValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeValueTypeAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableCellAddressAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableFormulaAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableMatrixCoveredAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableNumberMatrixColumnsSpannedAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableNumberMatrixRowsSpannedAttribute;
import org.odftoolkit.odfdom.dom.element.text.TextPElement;
import org.odftoolkit.odfdom.pkg.ElementVisitor;
import org.odftoolkit.odfdom.pkg.OdfElement;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/** DOM implementation of OpenDocument element {@odf.element table:change-track-table-cell}. */
public class TableChangeTrackTableCellElement extends OdfElement {
public static final OdfName ELEMENT_NAME =
OdfName.newName(OdfDocumentNamespace.TABLE, "change-track-table-cell");
/**
* Create the instance of <code>TableChangeTrackTableCellElement</code>
*
* @param ownerDoc The type is <code>OdfFileDom</code>
*/
public TableChangeTrackTableCellElement(OdfFileDom ownerDoc) {
super(ownerDoc, ELEMENT_NAME);
}
/**
* Get the element name
*
* @return return <code>OdfName</code> the name of element {@odf.element
* table:change-track-table-cell}.
*/
public OdfName getOdfName() {
return ELEMENT_NAME;
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeBooleanValueAttribute
* </code> , See {@odf.attribute office:boolean-value}
*
* @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Boolean getOfficeBooleanValueAttribute() {
OfficeBooleanValueAttribute attr =
(OfficeBooleanValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "boolean-value");
if (attr != null && !attr.getValue().isEmpty()) {
return Boolean.valueOf(attr.booleanValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeBooleanValueAttribute</code> ,
* See {@odf.attribute office:boolean-value}
*
* @param officeBooleanValueValue The type is <code>Boolean</code>
*/
public void setOfficeBooleanValueAttribute(Boolean officeBooleanValueValue) {
OfficeBooleanValueAttribute attr =
new OfficeBooleanValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setBooleanValue(officeBooleanValueValue.booleanValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeCurrencyAttribute</code>
* , See {@odf.attribute office:currency}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeCurrencyAttribute() {
OfficeCurrencyAttribute attr =
(OfficeCurrencyAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "currency");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeCurrencyAttribute</code> , See
* {@odf.attribute office:currency}
*
* @param officeCurrencyValue The type is <code>String</code>
*/
public void setOfficeCurrencyAttribute(String officeCurrencyValue) {
OfficeCurrencyAttribute attr = new OfficeCurrencyAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeCurrencyValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeDateValueAttribute</code>
* , See {@odf.attribute office:date-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeDateValueAttribute() {
OfficeDateValueAttribute attr =
(OfficeDateValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "date-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeDateValueAttribute</code> , See
* {@odf.attribute office:date-value}
*
* @param officeDateValueValue The type is <code>String</code>
*/
public void setOfficeDateValueAttribute(String officeDateValueValue) {
OfficeDateValueAttribute attr = new OfficeDateValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeDateValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeStringValueAttribute
* </code> , See {@odf.attribute office:string-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeStringValueAttribute() {
OfficeStringValueAttribute attr =
(OfficeStringValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "string-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeStringValueAttribute</code> , See
* {@odf.attribute office:string-value}
*
* @param officeStringValueValue The type is <code>String</code>
*/
public void setOfficeStringValueAttribute(String officeStringValueValue) {
OfficeStringValueAttribute attr =
new OfficeStringValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeStringValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeTimeValueAttribute</code>
* , See {@odf.attribute office:time-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeTimeValueAttribute() {
OfficeTimeValueAttribute attr =
(OfficeTimeValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "time-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeTimeValueAttribute</code> , See
* {@odf.attribute office:time-value}
*
* @param officeTimeValueValue The type is <code>String</code>
*/
public void setOfficeTimeValueAttribute(String officeTimeValueValue) {
OfficeTimeValueAttribute attr = new OfficeTimeValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeTimeValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeValueAttribute</code> ,
* See {@odf.attribute office:value}
*
* <p>Attribute is mandatory.
*
* @return - the <code>Double</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public Double getOfficeValueAttribute() {
OfficeValueAttribute attr =
(OfficeValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "value");
if (attr != null && !attr.getValue().isEmpty()) {
return Double.valueOf(attr.doubleValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeValueAttribute</code> , See
* {@odf.attribute office:value}
*
* @param officeValueValue The type is <code>Double</code>
*/
public void setOfficeValueAttribute(Double officeValueValue) {
OfficeValueAttribute attr = new OfficeValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setDoubleValue(officeValueValue.doubleValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeValueTypeAttribute</code>
* , See {@odf.attribute office:value-type}
*
* <p>Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeValueTypeAttribute() {
OfficeValueTypeAttribute attr =
(OfficeValueTypeAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "value-type");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeValueTypeAttribute</code> , See
* {@odf.attribute office:value-type}
*
* @param officeValueTypeValue The type is <code>String</code>
*/
public void setOfficeValueTypeAttribute(String officeValueTypeValue) {
OfficeValueTypeAttribute attr = new OfficeValueTypeAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeValueTypeValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableCellAddressAttribute
* </code> , See {@odf.attribute table:cell-address}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableCellAddressAttribute() {
TableCellAddressAttribute attr =
(TableCellAddressAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "cell-address");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableCellAddressAttribute</code> , See
* {@odf.attribute table:cell-address}
*
* @param tableCellAddressValue The type is <code>String</code>
*/
public void setTableCellAddressAttribute(String tableCellAddressValue) {
TableCellAddressAttribute attr = new TableCellAddressAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableCellAddressValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableFormulaAttribute</code> ,
* See {@odf.attribute table:formula}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableFormulaAttribute() {
TableFormulaAttribute attr =
(TableFormulaAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "formula");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableFormulaAttribute</code> , See
* {@odf.attribute table:formula}
*
* @param tableFormulaValue The type is <code>String</code>
*/
public void setTableFormulaAttribute(String tableFormulaValue) {
TableFormulaAttribute attr = new TableFormulaAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableFormulaValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableMatrixCoveredAttribute
* </code> , See {@odf.attribute table:matrix-covered}
*
* @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Boolean getTableMatrixCoveredAttribute() {
TableMatrixCoveredAttribute attr =
(TableMatrixCoveredAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "matrix-covered");
if (attr != null && !attr.getValue().isEmpty()) {
return Boolean.valueOf(attr.booleanValue());
}
return Boolean.valueOf(TableMatrixCoveredAttribute.DEFAULT_VALUE);
}
/**
* Sets the value of ODFDOM attribute representation <code>TableMatrixCoveredAttribute</code> ,
* See {@odf.attribute table:matrix-covered}
*
* @param tableMatrixCoveredValue The type is <code>Boolean</code>
*/
public void setTableMatrixCoveredAttribute(Boolean tableMatrixCoveredValue) {
TableMatrixCoveredAttribute attr =
new TableMatrixCoveredAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setBooleanValue(tableMatrixCoveredValue.booleanValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>
* TableNumberMatrixColumnsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-columns-spanned}
*
* @return - the <code>Integer</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Integer getTableNumberMatrixColumnsSpannedAttribute() {
TableNumberMatrixColumnsSpannedAttribute attr =
(TableNumberMatrixColumnsSpannedAttribute)
getOdfAttribute(OdfDocumentNamespace.TABLE, "number-matrix-columns-spanned");
if (attr != null && !attr.getValue().isEmpty()) {
return Integer.valueOf(attr.intValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>
* TableNumberMatrixColumnsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-columns-spanned}
*
* @param tableNumberMatrixColumnsSpannedValue The type is <code>Integer</code>
*/
public void setTableNumberMatrixColumnsSpannedAttribute(
Integer tableNumberMatrixColumnsSpannedValue) {
TableNumberMatrixColumnsSpannedAttribute attr =
new TableNumberMatrixColumnsSpannedAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setIntValue(tableNumberMatrixColumnsSpannedValue.intValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>
* TableNumberMatrixRowsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-rows-spanned}
*
* @return - the <code>Integer</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Integer getTableNumberMatrixRowsSpannedAttribute() {
TableNumberMatrixRowsSpannedAttribute attr =
(TableNumberMatrixRowsSpannedAttribute)
getOdfAttribute(OdfDocumentNamespace.TABLE, "number-matrix-rows-spanned");
if (attr != null && !attr.getValue().isEmpty()) {
return Integer.valueOf(attr.intValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableNumberMatrixRowsSpannedAttribute
* </code> , See {@odf.attribute table:number-matrix-rows-spanned}
*
* @param tableNumberMatrixRowsSpannedValue The type is <code>Integer</code>
*/
public void setTableNumberMatrixRowsSpannedAttribute(Integer tableNumberMatrixRowsSpannedValue) {
TableNumberMatrixRowsSpannedAttribute attr =
new TableNumberMatrixRowsSpannedAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setIntValue(tableNumberMatrixRowsSpannedValue.intValue());
}
/**
* Create child element {@odf.element text:p}.
*
* @return the element {@odf.element text:p}
*/
public TextPElement newTextPElement() {
TextPElement textP = ((OdfFileDom) this.ownerDocument).newOdfElement(TextPElement.class);
this.appendChild(textP);
return textP;
}
/**
* Accept an visitor instance to allow the visitor to do some operations. Refer to visitor design
* pattern to get a better understanding.
*
* @param visitor an instance of DefaultElementVisitor
*/
@Override
public void accept(ElementVisitor visitor) {
if (visitor instanceof DefaultElementVisitor) {
DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor;
defaultVisitor.visit(this);
} else {
visitor.visit(this);
}
}
/** Removes all the content from the element */
@Override
public void removeContent() {
super.removeContent();
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "value-type");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "time-value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "date-value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "boolean-value");
this.removeAttributeNS(
"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0", "value-type");
this.removeAttributeNS(OdfDocumentNamespace.TABLE.getUri(), "formula");
}
}
| tdf/odftoolkit | odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/table/TableChangeTrackTableCellElement.java | 5,281 | /**
* Create child element {@odf.element text:p}.
*
* @return the element {@odf.element text:p}
*/ | block_comment | nl | /**
* **********************************************************************
*
* <p>DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* <p>Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* <p>Use is subject to license terms.
*
* <p>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. You can also obtain a copy of the License at
* http://odftoolkit.org/docs/license.txt
*
* <p>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.
*
* <p>See the License for the specific language governing permissions and limitations under the
* License.
*
* <p>**********************************************************************
*/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.element.table;
import org.odftoolkit.odfdom.dom.DefaultElementVisitor;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeBooleanValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeCurrencyAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeDateValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeStringValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeTimeValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeValueAttribute;
import org.odftoolkit.odfdom.dom.attribute.office.OfficeValueTypeAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableCellAddressAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableFormulaAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableMatrixCoveredAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableNumberMatrixColumnsSpannedAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableNumberMatrixRowsSpannedAttribute;
import org.odftoolkit.odfdom.dom.element.text.TextPElement;
import org.odftoolkit.odfdom.pkg.ElementVisitor;
import org.odftoolkit.odfdom.pkg.OdfElement;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/** DOM implementation of OpenDocument element {@odf.element table:change-track-table-cell}. */
public class TableChangeTrackTableCellElement extends OdfElement {
public static final OdfName ELEMENT_NAME =
OdfName.newName(OdfDocumentNamespace.TABLE, "change-track-table-cell");
/**
* Create the instance of <code>TableChangeTrackTableCellElement</code>
*
* @param ownerDoc The type is <code>OdfFileDom</code>
*/
public TableChangeTrackTableCellElement(OdfFileDom ownerDoc) {
super(ownerDoc, ELEMENT_NAME);
}
/**
* Get the element name
*
* @return return <code>OdfName</code> the name of element {@odf.element
* table:change-track-table-cell}.
*/
public OdfName getOdfName() {
return ELEMENT_NAME;
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeBooleanValueAttribute
* </code> , See {@odf.attribute office:boolean-value}
*
* @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Boolean getOfficeBooleanValueAttribute() {
OfficeBooleanValueAttribute attr =
(OfficeBooleanValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "boolean-value");
if (attr != null && !attr.getValue().isEmpty()) {
return Boolean.valueOf(attr.booleanValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeBooleanValueAttribute</code> ,
* See {@odf.attribute office:boolean-value}
*
* @param officeBooleanValueValue The type is <code>Boolean</code>
*/
public void setOfficeBooleanValueAttribute(Boolean officeBooleanValueValue) {
OfficeBooleanValueAttribute attr =
new OfficeBooleanValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setBooleanValue(officeBooleanValueValue.booleanValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeCurrencyAttribute</code>
* , See {@odf.attribute office:currency}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeCurrencyAttribute() {
OfficeCurrencyAttribute attr =
(OfficeCurrencyAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "currency");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeCurrencyAttribute</code> , See
* {@odf.attribute office:currency}
*
* @param officeCurrencyValue The type is <code>String</code>
*/
public void setOfficeCurrencyAttribute(String officeCurrencyValue) {
OfficeCurrencyAttribute attr = new OfficeCurrencyAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeCurrencyValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeDateValueAttribute</code>
* , See {@odf.attribute office:date-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeDateValueAttribute() {
OfficeDateValueAttribute attr =
(OfficeDateValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "date-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeDateValueAttribute</code> , See
* {@odf.attribute office:date-value}
*
* @param officeDateValueValue The type is <code>String</code>
*/
public void setOfficeDateValueAttribute(String officeDateValueValue) {
OfficeDateValueAttribute attr = new OfficeDateValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeDateValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeStringValueAttribute
* </code> , See {@odf.attribute office:string-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeStringValueAttribute() {
OfficeStringValueAttribute attr =
(OfficeStringValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "string-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeStringValueAttribute</code> , See
* {@odf.attribute office:string-value}
*
* @param officeStringValueValue The type is <code>String</code>
*/
public void setOfficeStringValueAttribute(String officeStringValueValue) {
OfficeStringValueAttribute attr =
new OfficeStringValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeStringValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeTimeValueAttribute</code>
* , See {@odf.attribute office:time-value}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeTimeValueAttribute() {
OfficeTimeValueAttribute attr =
(OfficeTimeValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "time-value");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeTimeValueAttribute</code> , See
* {@odf.attribute office:time-value}
*
* @param officeTimeValueValue The type is <code>String</code>
*/
public void setOfficeTimeValueAttribute(String officeTimeValueValue) {
OfficeTimeValueAttribute attr = new OfficeTimeValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeTimeValueValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeValueAttribute</code> ,
* See {@odf.attribute office:value}
*
* <p>Attribute is mandatory.
*
* @return - the <code>Double</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public Double getOfficeValueAttribute() {
OfficeValueAttribute attr =
(OfficeValueAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "value");
if (attr != null && !attr.getValue().isEmpty()) {
return Double.valueOf(attr.doubleValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeValueAttribute</code> , See
* {@odf.attribute office:value}
*
* @param officeValueValue The type is <code>Double</code>
*/
public void setOfficeValueAttribute(Double officeValueValue) {
OfficeValueAttribute attr = new OfficeValueAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setDoubleValue(officeValueValue.doubleValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>OfficeValueTypeAttribute</code>
* , See {@odf.attribute office:value-type}
*
* <p>Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getOfficeValueTypeAttribute() {
OfficeValueTypeAttribute attr =
(OfficeValueTypeAttribute) getOdfAttribute(OdfDocumentNamespace.OFFICE, "value-type");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>OfficeValueTypeAttribute</code> , See
* {@odf.attribute office:value-type}
*
* @param officeValueTypeValue The type is <code>String</code>
*/
public void setOfficeValueTypeAttribute(String officeValueTypeValue) {
OfficeValueTypeAttribute attr = new OfficeValueTypeAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(officeValueTypeValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableCellAddressAttribute
* </code> , See {@odf.attribute table:cell-address}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableCellAddressAttribute() {
TableCellAddressAttribute attr =
(TableCellAddressAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "cell-address");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableCellAddressAttribute</code> , See
* {@odf.attribute table:cell-address}
*
* @param tableCellAddressValue The type is <code>String</code>
*/
public void setTableCellAddressAttribute(String tableCellAddressValue) {
TableCellAddressAttribute attr = new TableCellAddressAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableCellAddressValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableFormulaAttribute</code> ,
* See {@odf.attribute table:formula}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableFormulaAttribute() {
TableFormulaAttribute attr =
(TableFormulaAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "formula");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableFormulaAttribute</code> , See
* {@odf.attribute table:formula}
*
* @param tableFormulaValue The type is <code>String</code>
*/
public void setTableFormulaAttribute(String tableFormulaValue) {
TableFormulaAttribute attr = new TableFormulaAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableFormulaValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableMatrixCoveredAttribute
* </code> , See {@odf.attribute table:matrix-covered}
*
* @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Boolean getTableMatrixCoveredAttribute() {
TableMatrixCoveredAttribute attr =
(TableMatrixCoveredAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "matrix-covered");
if (attr != null && !attr.getValue().isEmpty()) {
return Boolean.valueOf(attr.booleanValue());
}
return Boolean.valueOf(TableMatrixCoveredAttribute.DEFAULT_VALUE);
}
/**
* Sets the value of ODFDOM attribute representation <code>TableMatrixCoveredAttribute</code> ,
* See {@odf.attribute table:matrix-covered}
*
* @param tableMatrixCoveredValue The type is <code>Boolean</code>
*/
public void setTableMatrixCoveredAttribute(Boolean tableMatrixCoveredValue) {
TableMatrixCoveredAttribute attr =
new TableMatrixCoveredAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setBooleanValue(tableMatrixCoveredValue.booleanValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>
* TableNumberMatrixColumnsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-columns-spanned}
*
* @return - the <code>Integer</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Integer getTableNumberMatrixColumnsSpannedAttribute() {
TableNumberMatrixColumnsSpannedAttribute attr =
(TableNumberMatrixColumnsSpannedAttribute)
getOdfAttribute(OdfDocumentNamespace.TABLE, "number-matrix-columns-spanned");
if (attr != null && !attr.getValue().isEmpty()) {
return Integer.valueOf(attr.intValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>
* TableNumberMatrixColumnsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-columns-spanned}
*
* @param tableNumberMatrixColumnsSpannedValue The type is <code>Integer</code>
*/
public void setTableNumberMatrixColumnsSpannedAttribute(
Integer tableNumberMatrixColumnsSpannedValue) {
TableNumberMatrixColumnsSpannedAttribute attr =
new TableNumberMatrixColumnsSpannedAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setIntValue(tableNumberMatrixColumnsSpannedValue.intValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>
* TableNumberMatrixRowsSpannedAttribute</code> , See {@odf.attribute
* table:number-matrix-rows-spanned}
*
* @return - the <code>Integer</code> , the value or <code>null</code>, if the attribute is not
* set and no default value defined.
*/
public Integer getTableNumberMatrixRowsSpannedAttribute() {
TableNumberMatrixRowsSpannedAttribute attr =
(TableNumberMatrixRowsSpannedAttribute)
getOdfAttribute(OdfDocumentNamespace.TABLE, "number-matrix-rows-spanned");
if (attr != null && !attr.getValue().isEmpty()) {
return Integer.valueOf(attr.intValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableNumberMatrixRowsSpannedAttribute
* </code> , See {@odf.attribute table:number-matrix-rows-spanned}
*
* @param tableNumberMatrixRowsSpannedValue The type is <code>Integer</code>
*/
public void setTableNumberMatrixRowsSpannedAttribute(Integer tableNumberMatrixRowsSpannedValue) {
TableNumberMatrixRowsSpannedAttribute attr =
new TableNumberMatrixRowsSpannedAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setIntValue(tableNumberMatrixRowsSpannedValue.intValue());
}
/**
* Create child element<SUF>*/
public TextPElement newTextPElement() {
TextPElement textP = ((OdfFileDom) this.ownerDocument).newOdfElement(TextPElement.class);
this.appendChild(textP);
return textP;
}
/**
* Accept an visitor instance to allow the visitor to do some operations. Refer to visitor design
* pattern to get a better understanding.
*
* @param visitor an instance of DefaultElementVisitor
*/
@Override
public void accept(ElementVisitor visitor) {
if (visitor instanceof DefaultElementVisitor) {
DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor;
defaultVisitor.visit(this);
} else {
visitor.visit(this);
}
}
/** Removes all the content from the element */
@Override
public void removeContent() {
super.removeContent();
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "value-type");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "time-value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "date-value");
this.removeAttributeNS(OdfDocumentNamespace.OFFICE.getUri(), "boolean-value");
this.removeAttributeNS(
"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0", "value-type");
this.removeAttributeNS(OdfDocumentNamespace.TABLE.getUri(), "formula");
}
}
|
178705_24 | package Jaybot.YOLOBOT.Util.Planner;
import core.game.Observation;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.PlayerEvent;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloEvent;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloKnowledge;
import Jaybot.YOLOBOT.YoloState;
import ontology.Types;
import ontology.Types.ACTIONS;
import java.util.*;
public class KnowledgeBasedAStar {
public static final int MALUS = 40;
private List<Observation>[][] grid;
public int[][] distance;
public int[][] fromAvatarDistance;
public byte[][] originDirectionArray;
public int[][] ausnahmeID;
public boolean[][] interpretedAsWall;
public int[] fieldsReachedCount;
private boolean stopEarly;
private int stopEarlyX, stopEarlyY;
private boolean extraIllegalMove;
private int extraIllegalMoveX, extraIllegalMoveY, extraIllegalMoveItype;
private int oneMoveableIgnoreIType;
private byte[] zycleMet;
private Collection<Integer> blacklistedObjects;
public int[] iTypesFoundCount;
public Observation[] nearestITypeObservationFound;
public int[] nearestITypeObservationFoundFirstTargetX;
public int[] nearestITypeObservationFoundFirstTargetY;
private boolean countFoundItypes;
private HashSet<Integer> countedObsIds;
private int[] possibleMovesX, possibleMovesY;
/***
* Direction from where it got reached.<br/>
* 0 = Left<br/>
* 1 = Right<br/>
* 2 = Top<br/>
* 3 = Bottom<br/>
* 5 = By Portal
*/
public byte[][] from;
public final static byte LEFT = 0;
public final static byte RIGHT = 1;
public final static byte TOP = 2;
public final static byte BOTTOM = 3;
private static boolean[] markedItypes;
private byte[] inventoryItems;
private YoloState state;
private boolean moveDirectionInverse;
public KnowledgeBasedAStar(YoloState yoloState) {
this.state = yoloState;
this.grid = yoloState.getObservationGrid();
inventoryItems = yoloState.getInventoryArray();
oneMoveableIgnoreIType = -1;
countFoundItypes = false;
moveDirectionInverse = false;
ArrayList<ACTIONS> actions = yoloState.getAvailableActions();
//TODO use action?
int actionsSize = actions.size() - (actions.contains(ACTIONS.ACTION_USE)?1:0);
possibleMovesX = new int[actionsSize];
possibleMovesY = new int[actionsSize];
int ignoredActions = 0;
for (int i = 0; i < actions.size(); i++) {
switch (actions.get(i)) {
case ACTION_DOWN:
possibleMovesY[i-ignoredActions] = 1;
break;
case ACTION_UP:
possibleMovesY[i-ignoredActions] = -1;
break;
case ACTION_RIGHT:
possibleMovesX[i-ignoredActions] = 1;
break;
case ACTION_LEFT:
possibleMovesX[i-ignoredActions] = -1;
break;
default:
ignoredActions++;
break;
}
}
}
public void setIllegalMove(int x, int y, int itype){
extraIllegalMove = true;
extraIllegalMoveX = x;
extraIllegalMoveY = y;
extraIllegalMoveItype = itype;
}
public void disableIllegalMove(){
extraIllegalMove = false;
}
public void setStopEarly(int x, int y){
stopEarly = true;
stopEarlyX = x;
stopEarlyY = y;
}
public void disableStopEarly(){
stopEarly = false;
}
public void setGrid(List<Observation>[][] grid) {
this.grid = grid;
}
public List<Observation> calculate(int startX, int startY, int agent_itype_start,
int[] interestingItypes, boolean ignoreMoveables) {
return calculate(startX, startY, agent_itype_start, interestingItypes, ignoreMoveables, false, true);
}
public List<Observation> calculate(int startX, int startY, int agent_itype_start,
int[] interestingItypes, boolean ignoreMoveables, boolean ignoreNPC, boolean ignorePortals) {
LinkedList<Observation> retVal = new LinkedList<Observation>();
if(!YoloKnowledge.instance.positionAufSpielfeld(startX, startY))
return null;
if(countFoundItypes){
iTypesFoundCount = new int[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFound = new Observation[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFoundFirstTargetX = new int[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFoundFirstTargetY = new int[YoloKnowledge.ITYPE_MAX_COUNT];
countedObsIds = new HashSet<Integer>();
}
fieldsReachedCount = new int[4];
zycleMet = new byte[]{0b0001,0b0010,0b0100,0b1000};
markedItypes = new boolean[YoloKnowledge.ITYPE_MAX_COUNT];
for (int i = 0; i < interestingItypes.length; i++) {
if(interestingItypes[i] != -1)
markedItypes[interestingItypes[i]] = true;
}
originDirectionArray = new byte[grid.length][grid[0].length];
distance = new int[grid.length][grid[0].length];
ausnahmeID = new int[grid.length][grid[0].length];
distance[startX][startY] = 1;
from = new byte[grid.length][grid[0].length];
interpretedAsWall = new boolean[grid.length][grid[0].length];
PriorityQueue<AStarEntry> queue = new PriorityQueue<AStarEntry>();
queue.add(new AStarEntry(startX, startY, agent_itype_start, oneMoveableIgnoreIType, (byte)-1, 1, -1, -1));
if(countFoundItypes){
for (Observation obs : grid[startX][startY]) {
if(countedObsIds.contains(obs.obsID))
continue;
countedObsIds.add(obs.obsID);
int index = YoloKnowledge.instance.itypeToIndex(obs.itype);
if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID))
continue;
int oldVal = iTypesFoundCount[index]++;
if(oldVal == 0){
//Nearest Observation of this itype:
nearestITypeObservationFound[index] = obs;
nearestITypeObservationFoundFirstTargetX[index] = startX;
nearestITypeObservationFoundFirstTargetY[index] = startY;
}
}
}
while (queue.size() > 0) {
AStarEntry oldEntry = queue.poll();
int x = oldEntry.getX();
int y = oldEntry.getY();
int agent_itype = oldEntry.getItype();
int itypeAusnahme = oldEntry.getItypeAusnahme();
int oldDistance = oldEntry.getDistance();
byte fromDirectionOld = oldEntry.getOriginAusrichtung();
int changedItypeX = oldEntry.getxFirstItypeChange();
int changedItypeY = oldEntry.getyFirstItypeChange();
for (int i = 0; i < possibleMovesX.length; i++) {
int xNew = x + possibleMovesX[i];
int yNew = y + possibleMovesY[i];
int newDistance = oldDistance + 1;
byte fromDirection = fromDirectionOld;
if (xNew >= 0 && xNew < grid.length && yNew >= 0 && yNew < grid[xNew].length && (xNew == x || yNew == y)){
//First-step-check:
if(fromDirection == -1){
//Is first step:
if(possibleMovesX[i]>0)
fromDirection = RIGHT;
else if(possibleMovesX[i] < 0)
fromDirection = LEFT;
if(possibleMovesY[i]>0)
fromDirection = BOTTOM;
else if(possibleMovesY[i] < 0)
fromDirection = TOP;
}
//Gueltiges Feld
if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){
//Neu gefunden!
boolean moveBlocked = false;
boolean isPortalEntry = false;
int deadlyField = canBeKilledAtByStochasticEnemy(xNew, yNew);
int new_itype = agent_itype;
int portalIType = -1;
boolean[] blockedBy = new boolean[grid[xNew][yNew].size()];
boolean[] useActionEffective = new boolean[grid[xNew][yNew].size()];
int nr = 0;
for (Observation obs : grid[xNew][yNew]) {
if(ignoreNPC && obs.category == Types.TYPE_NPC){// && (fromAvatarDistance == null || fromAvatarDistance[xNew][yNew] > 5) && (fromAvatarDistance != null || distance[xNew][yNew] > 5)){
continue;
}
if(obs.category == Types.TYPE_PORTAL){
if(!moveDirectionInverse)
portalIType = obs.itype;
PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true);
YoloEvent event = pEvent.getEvent(inventoryItems);
if(!pEvent.willCancel(inventoryItems) && event.getTeleportTo() != -1)
isPortalEntry = true;
}
if(moveDirectionInverse){
int fromTeleport = YoloKnowledge.instance.getPortalExitEntryIType(YoloKnowledge.instance.itypeToIndex(obs.itype));
portalIType = fromTeleport;
}
if(obs.category != Types.TYPE_AVATAR){
int passiveIndex = YoloKnowledge.instance.itypeToIndex(obs.itype);
PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true);
int spawnIndex = YoloKnowledge.instance.getSpawnIndexOfSpawner(obs.itype);
boolean isBadSpawner = false;
if(spawnIndex != -1){
//Etwas wird gespawnt!
PlayerEvent spawnCollisionEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, YoloKnowledge.instance.indexToItype(spawnIndex), true);
if(spawnCollisionEvent.getObserveCount() > 0){
YoloEvent yEvent = spawnCollisionEvent.getEvent(inventoryItems);
isBadSpawner = yEvent.getKill() || yEvent.getScoreDelta() < 0 || yEvent.getRemoveInventorySlotItem() != -1;
}
}
boolean interactable = YoloKnowledge.instance.canInteractWithUse(agent_itype, obs.itype);
useActionEffective[nr] = interactable;
boolean deadly = event.getEvent(inventoryItems).getKill() && !YoloKnowledge.instance.hasEverBeenAliveAtFieldWithItypeIndex(YoloKnowledge.instance.itypeToIndex(agent_itype),passiveIndex) && obs.category != Types.TYPE_MOVABLE;
if(deadly)
deadlyField = 0;
blockedBy[nr] = isBadSpawner || (event.getObserveCount() > 0 && (event.willCancel(inventoryItems) || !event.getEvent(inventoryItems).getMove() || (deadly ))) && !interactable;
if(!(moveBlocked||blockedBy[nr]) && !ignoreMoveables && event.getObserveCount() > 0){
if(obs.category == Types.TYPE_MOVABLE && !event.getEvent(inventoryItems).getMove()){
//Hier wird wegen eines MOVEABLES geblockt! Teste oneMoveableIgnoreIType
if(itypeAusnahme == obs.itype){
//Ausnahme trifft ein, dass ein bestimmter IType ein mal ignoriert werden darf!
ausnahmeID[xNew][yNew] = obs.obsID;
itypeAusnahme = -1;
}else{
//Keine Ausnahme!
blockedBy[nr] = true;
}
}
}
moveBlocked |= blockedBy[nr];
if(markedItypes[obs.itype])
retVal.add(obs);
if(!moveBlocked){
int modType = event.getEvent(inventoryItems).getIType();
if(modType != -1){
new_itype = YoloKnowledge.instance.indexToItype(modType);
if(changedItypeX == -1 && changedItypeY == -1){
// not yet changed Itype:
changedItypeX = xNew;
changedItypeY = yNew;
}
}
}
}
nr++;
}
if(deadlyField != Integer.MAX_VALUE)
newDistance += 2*MALUS/(deadlyField+1);
moveBlocked |= !ignorePortals && isPortalEntry && moveDirectionInverse;
if(!moveBlocked && extraIllegalMove && extraIllegalMoveX == xNew && extraIllegalMoveY == yNew){
//Stepping on illegal field
PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, extraIllegalMoveItype, false); //Was passiert mit dem passive?
YoloEvent triggeredEvent = event.getEvent(inventoryItems);
if(triggeredEvent.getMove() || event.getObserveCount() == 0) //Passive bewegt sich?
moveBlocked = true;
}
if(distance[xNew][yNew] == 0 || (interpretedAsWall[xNew][yNew] && !moveBlocked)){
distance[xNew][yNew] = newDistance;
from[xNew][yNew] = (byte)((xNew < x?0:(xNew > x?1:(yNew < y?2:3))));
}
interpretedAsWall[xNew][yNew] = moveBlocked;
//Count appearances:
if(countFoundItypes && deadlyField > 1){
nr = -1;
for (Observation obs : grid[xNew][yNew]) {
nr++;
if(countedObsIds.contains(obs.obsID) || (moveBlocked && !blockedBy[nr] && !useActionEffective[nr]))
continue;
countedObsIds.add(obs.obsID);
int index = YoloKnowledge.instance.itypeToIndex(obs.itype);
if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID))
continue;
int oldVal = iTypesFoundCount[index]++;
if(oldVal == 0){
//Nearest Observation of this itype:
nearestITypeObservationFound[index] = obs;
if(changedItypeX != -1 && changedItypeY != -1){
//Itype has been changed, so move frist to Itypechange!
nearestITypeObservationFoundFirstTargetX[index] = changedItypeX;
nearestITypeObservationFoundFirstTargetY[index] = changedItypeY;
}else{
//Itype has not been changed, move to object
nearestITypeObservationFoundFirstTargetX[index] = xNew;
nearestITypeObservationFoundFirstTargetY[index] = yNew;
}
}
}
}
if(!moveBlocked){
fieldsReachedCount[fromDirection]++;
originDirectionArray[xNew][yNew] = fromDirection;
//Early Stop
if(stopEarly && xNew == stopEarlyX && yNew == stopEarlyY)
return retVal;
boolean teleported = false;
if(portalIType != -1 && !ignorePortals){
int portalExitIType = -1, portalExitIndex;
if(!moveDirectionInverse){
PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, portalIType, true);
YoloEvent event = pEvent.getEvent(inventoryItems);
portalExitIndex = event.getTeleportTo();
if(!pEvent.willCancel(inventoryItems) && portalExitIndex != -1)
portalExitIType = YoloKnowledge.instance.indexToItype(portalExitIndex);
}else{
portalExitIType = portalIType;
portalExitIndex = YoloKnowledge.instance.itypeToIndex(portalExitIType);
}
if(portalExitIType != -1){
int portalExitCategory = YoloKnowledge.instance.getObjectCategory(portalExitIndex, state);
if(portalExitCategory != -1){
ArrayList<Observation>[] obs = state.getObservationList(portalExitCategory);
if(obs != null){
ArrayList<Observation> portalExits = null;
for (ArrayList<Observation> list : obs) {
if(!list.isEmpty() && list.get(0).itype == portalExitIType)
portalExits = list;
}
if(portalExits != null){
//Habe Portalausgaenge gefunden!
teleported = true;
int blockSize = state.getBlockSize();
for (Observation exit : portalExits) {
xNew = (int)exit.position.x/blockSize;
yNew = (int)exit.position.y/blockSize;
if(xNew < 0 || yNew < 0 || xNew >= distance.length ||yNew >= distance[xNew].length)
continue;
if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){
//Hier war die SUche noch nicht!
from[xNew][yNew] = 5;
originDirectionArray[xNew][yNew] = fromDirection;
distance[xNew][yNew] = newDistance;
queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY));
}else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){
//Hier waren wir schon, untersuche zyklus
handleZyklus(fromDirection, originDirectionArray[xNew][yNew]);
}
}
}
}
}
}
}
if(!teleported){
//Standard appending for later loop
queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY));
}
}
}else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){
//Hier waren wir schon, untersuche zyklus
handleZyklus(fromDirection, originDirectionArray[xNew][yNew]);
}
}
}
}
//Postwork - zycles:
for (int iteration = 0; iteration < 2; iteration++) {
for (int from = 0; from < zycleMet.length; from++) {
for (int to = 0; to < 4; to++) {
if(to == from)
continue;
if((zycleMet[from]>>to & 1) == 1){
//from hat zykel zu to
byte newMask = (byte) (zycleMet[from] | zycleMet[to]);
zycleMet[from] = newMask;
zycleMet[to] = newMask;
}
}
}
}
int[] oldFieldReached = new int[]{fieldsReachedCount[0],fieldsReachedCount[1],fieldsReachedCount[2],fieldsReachedCount[3]};
for (int from = 0; from < zycleMet.length; from++) {
fieldsReachedCount[from] = 0;
for (int to = 0; to < 4; to++) {
if((zycleMet[from]>>to & 1) == 1){
//from hat zykel zu to
fieldsReachedCount[from] += oldFieldReached[to];
}
}
}
return retVal;
}
private int canBeKilledAtByStochasticEnemy(int x, int y){
return state.getStochasticKillMap().getMinDistanceToEnemy(x,y);
}
public LinkedList<ACTIONS> extractActions(int xTarget, int yTarget) {
LinkedList<ACTIONS> actionsToDo = new LinkedList<ACTIONS>();
if (distance[xTarget][yTarget] > 1) {
// Weg gefunden(!= 0) und bewegen notwendig(!= 1)
int curX = xTarget;
int curY = yTarget;
while (distance[curX][curY] > 1) {
switch (from[curX][curY]) {
case KnowledgeBasedAStar.BOTTOM:
actionsToDo.addFirst(ACTIONS.ACTION_DOWN);
curY--;
break;
case KnowledgeBasedAStar.TOP:
actionsToDo.addFirst(ACTIONS.ACTION_UP);
curY++;
break;
case KnowledgeBasedAStar.LEFT:
actionsToDo.addFirst(ACTIONS.ACTION_LEFT);
curX++;
break;
case KnowledgeBasedAStar.RIGHT:
actionsToDo.addFirst(ACTIONS.ACTION_RIGHT);
curX--;
break;
default:
//TODO: Portal-Case beachten!
System.err.println("Portal gefunden, aber 'extractActions' wurde noch nicht passend implementiert!!");
break;
}
}
}
return actionsToDo;
}
public void setIgnoreOneMoveableOfType(int itype) {
oneMoveableIgnoreIType = itype;
}
public void setCountFoundItypes(boolean value) {
this.countFoundItypes = value;
}
public void setMoveDirectionInverse(boolean value) {
moveDirectionInverse = value;
fromAvatarDistance = distance;
}
private void handleZyklus(byte direction1, byte direction2){
zycleMet[direction1] |= 1<<direction2;
}
public void setBlacklistedObjects(Collection<Integer> blacklistedObjects) {
this.blacklistedObjects = blacklistedObjects;
}
}
| teaCube/Jaybot | src/main/java/Jaybot/YOLOBOT/Util/Planner/KnowledgeBasedAStar.java | 6,559 | //TODO: Portal-Case beachten! | line_comment | nl | package Jaybot.YOLOBOT.Util.Planner;
import core.game.Observation;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.PlayerEvent;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloEvent;
import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloKnowledge;
import Jaybot.YOLOBOT.YoloState;
import ontology.Types;
import ontology.Types.ACTIONS;
import java.util.*;
public class KnowledgeBasedAStar {
public static final int MALUS = 40;
private List<Observation>[][] grid;
public int[][] distance;
public int[][] fromAvatarDistance;
public byte[][] originDirectionArray;
public int[][] ausnahmeID;
public boolean[][] interpretedAsWall;
public int[] fieldsReachedCount;
private boolean stopEarly;
private int stopEarlyX, stopEarlyY;
private boolean extraIllegalMove;
private int extraIllegalMoveX, extraIllegalMoveY, extraIllegalMoveItype;
private int oneMoveableIgnoreIType;
private byte[] zycleMet;
private Collection<Integer> blacklistedObjects;
public int[] iTypesFoundCount;
public Observation[] nearestITypeObservationFound;
public int[] nearestITypeObservationFoundFirstTargetX;
public int[] nearestITypeObservationFoundFirstTargetY;
private boolean countFoundItypes;
private HashSet<Integer> countedObsIds;
private int[] possibleMovesX, possibleMovesY;
/***
* Direction from where it got reached.<br/>
* 0 = Left<br/>
* 1 = Right<br/>
* 2 = Top<br/>
* 3 = Bottom<br/>
* 5 = By Portal
*/
public byte[][] from;
public final static byte LEFT = 0;
public final static byte RIGHT = 1;
public final static byte TOP = 2;
public final static byte BOTTOM = 3;
private static boolean[] markedItypes;
private byte[] inventoryItems;
private YoloState state;
private boolean moveDirectionInverse;
public KnowledgeBasedAStar(YoloState yoloState) {
this.state = yoloState;
this.grid = yoloState.getObservationGrid();
inventoryItems = yoloState.getInventoryArray();
oneMoveableIgnoreIType = -1;
countFoundItypes = false;
moveDirectionInverse = false;
ArrayList<ACTIONS> actions = yoloState.getAvailableActions();
//TODO use action?
int actionsSize = actions.size() - (actions.contains(ACTIONS.ACTION_USE)?1:0);
possibleMovesX = new int[actionsSize];
possibleMovesY = new int[actionsSize];
int ignoredActions = 0;
for (int i = 0; i < actions.size(); i++) {
switch (actions.get(i)) {
case ACTION_DOWN:
possibleMovesY[i-ignoredActions] = 1;
break;
case ACTION_UP:
possibleMovesY[i-ignoredActions] = -1;
break;
case ACTION_RIGHT:
possibleMovesX[i-ignoredActions] = 1;
break;
case ACTION_LEFT:
possibleMovesX[i-ignoredActions] = -1;
break;
default:
ignoredActions++;
break;
}
}
}
public void setIllegalMove(int x, int y, int itype){
extraIllegalMove = true;
extraIllegalMoveX = x;
extraIllegalMoveY = y;
extraIllegalMoveItype = itype;
}
public void disableIllegalMove(){
extraIllegalMove = false;
}
public void setStopEarly(int x, int y){
stopEarly = true;
stopEarlyX = x;
stopEarlyY = y;
}
public void disableStopEarly(){
stopEarly = false;
}
public void setGrid(List<Observation>[][] grid) {
this.grid = grid;
}
public List<Observation> calculate(int startX, int startY, int agent_itype_start,
int[] interestingItypes, boolean ignoreMoveables) {
return calculate(startX, startY, agent_itype_start, interestingItypes, ignoreMoveables, false, true);
}
public List<Observation> calculate(int startX, int startY, int agent_itype_start,
int[] interestingItypes, boolean ignoreMoveables, boolean ignoreNPC, boolean ignorePortals) {
LinkedList<Observation> retVal = new LinkedList<Observation>();
if(!YoloKnowledge.instance.positionAufSpielfeld(startX, startY))
return null;
if(countFoundItypes){
iTypesFoundCount = new int[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFound = new Observation[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFoundFirstTargetX = new int[YoloKnowledge.ITYPE_MAX_COUNT];
nearestITypeObservationFoundFirstTargetY = new int[YoloKnowledge.ITYPE_MAX_COUNT];
countedObsIds = new HashSet<Integer>();
}
fieldsReachedCount = new int[4];
zycleMet = new byte[]{0b0001,0b0010,0b0100,0b1000};
markedItypes = new boolean[YoloKnowledge.ITYPE_MAX_COUNT];
for (int i = 0; i < interestingItypes.length; i++) {
if(interestingItypes[i] != -1)
markedItypes[interestingItypes[i]] = true;
}
originDirectionArray = new byte[grid.length][grid[0].length];
distance = new int[grid.length][grid[0].length];
ausnahmeID = new int[grid.length][grid[0].length];
distance[startX][startY] = 1;
from = new byte[grid.length][grid[0].length];
interpretedAsWall = new boolean[grid.length][grid[0].length];
PriorityQueue<AStarEntry> queue = new PriorityQueue<AStarEntry>();
queue.add(new AStarEntry(startX, startY, agent_itype_start, oneMoveableIgnoreIType, (byte)-1, 1, -1, -1));
if(countFoundItypes){
for (Observation obs : grid[startX][startY]) {
if(countedObsIds.contains(obs.obsID))
continue;
countedObsIds.add(obs.obsID);
int index = YoloKnowledge.instance.itypeToIndex(obs.itype);
if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID))
continue;
int oldVal = iTypesFoundCount[index]++;
if(oldVal == 0){
//Nearest Observation of this itype:
nearestITypeObservationFound[index] = obs;
nearestITypeObservationFoundFirstTargetX[index] = startX;
nearestITypeObservationFoundFirstTargetY[index] = startY;
}
}
}
while (queue.size() > 0) {
AStarEntry oldEntry = queue.poll();
int x = oldEntry.getX();
int y = oldEntry.getY();
int agent_itype = oldEntry.getItype();
int itypeAusnahme = oldEntry.getItypeAusnahme();
int oldDistance = oldEntry.getDistance();
byte fromDirectionOld = oldEntry.getOriginAusrichtung();
int changedItypeX = oldEntry.getxFirstItypeChange();
int changedItypeY = oldEntry.getyFirstItypeChange();
for (int i = 0; i < possibleMovesX.length; i++) {
int xNew = x + possibleMovesX[i];
int yNew = y + possibleMovesY[i];
int newDistance = oldDistance + 1;
byte fromDirection = fromDirectionOld;
if (xNew >= 0 && xNew < grid.length && yNew >= 0 && yNew < grid[xNew].length && (xNew == x || yNew == y)){
//First-step-check:
if(fromDirection == -1){
//Is first step:
if(possibleMovesX[i]>0)
fromDirection = RIGHT;
else if(possibleMovesX[i] < 0)
fromDirection = LEFT;
if(possibleMovesY[i]>0)
fromDirection = BOTTOM;
else if(possibleMovesY[i] < 0)
fromDirection = TOP;
}
//Gueltiges Feld
if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){
//Neu gefunden!
boolean moveBlocked = false;
boolean isPortalEntry = false;
int deadlyField = canBeKilledAtByStochasticEnemy(xNew, yNew);
int new_itype = agent_itype;
int portalIType = -1;
boolean[] blockedBy = new boolean[grid[xNew][yNew].size()];
boolean[] useActionEffective = new boolean[grid[xNew][yNew].size()];
int nr = 0;
for (Observation obs : grid[xNew][yNew]) {
if(ignoreNPC && obs.category == Types.TYPE_NPC){// && (fromAvatarDistance == null || fromAvatarDistance[xNew][yNew] > 5) && (fromAvatarDistance != null || distance[xNew][yNew] > 5)){
continue;
}
if(obs.category == Types.TYPE_PORTAL){
if(!moveDirectionInverse)
portalIType = obs.itype;
PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true);
YoloEvent event = pEvent.getEvent(inventoryItems);
if(!pEvent.willCancel(inventoryItems) && event.getTeleportTo() != -1)
isPortalEntry = true;
}
if(moveDirectionInverse){
int fromTeleport = YoloKnowledge.instance.getPortalExitEntryIType(YoloKnowledge.instance.itypeToIndex(obs.itype));
portalIType = fromTeleport;
}
if(obs.category != Types.TYPE_AVATAR){
int passiveIndex = YoloKnowledge.instance.itypeToIndex(obs.itype);
PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true);
int spawnIndex = YoloKnowledge.instance.getSpawnIndexOfSpawner(obs.itype);
boolean isBadSpawner = false;
if(spawnIndex != -1){
//Etwas wird gespawnt!
PlayerEvent spawnCollisionEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, YoloKnowledge.instance.indexToItype(spawnIndex), true);
if(spawnCollisionEvent.getObserveCount() > 0){
YoloEvent yEvent = spawnCollisionEvent.getEvent(inventoryItems);
isBadSpawner = yEvent.getKill() || yEvent.getScoreDelta() < 0 || yEvent.getRemoveInventorySlotItem() != -1;
}
}
boolean interactable = YoloKnowledge.instance.canInteractWithUse(agent_itype, obs.itype);
useActionEffective[nr] = interactable;
boolean deadly = event.getEvent(inventoryItems).getKill() && !YoloKnowledge.instance.hasEverBeenAliveAtFieldWithItypeIndex(YoloKnowledge.instance.itypeToIndex(agent_itype),passiveIndex) && obs.category != Types.TYPE_MOVABLE;
if(deadly)
deadlyField = 0;
blockedBy[nr] = isBadSpawner || (event.getObserveCount() > 0 && (event.willCancel(inventoryItems) || !event.getEvent(inventoryItems).getMove() || (deadly ))) && !interactable;
if(!(moveBlocked||blockedBy[nr]) && !ignoreMoveables && event.getObserveCount() > 0){
if(obs.category == Types.TYPE_MOVABLE && !event.getEvent(inventoryItems).getMove()){
//Hier wird wegen eines MOVEABLES geblockt! Teste oneMoveableIgnoreIType
if(itypeAusnahme == obs.itype){
//Ausnahme trifft ein, dass ein bestimmter IType ein mal ignoriert werden darf!
ausnahmeID[xNew][yNew] = obs.obsID;
itypeAusnahme = -1;
}else{
//Keine Ausnahme!
blockedBy[nr] = true;
}
}
}
moveBlocked |= blockedBy[nr];
if(markedItypes[obs.itype])
retVal.add(obs);
if(!moveBlocked){
int modType = event.getEvent(inventoryItems).getIType();
if(modType != -1){
new_itype = YoloKnowledge.instance.indexToItype(modType);
if(changedItypeX == -1 && changedItypeY == -1){
// not yet changed Itype:
changedItypeX = xNew;
changedItypeY = yNew;
}
}
}
}
nr++;
}
if(deadlyField != Integer.MAX_VALUE)
newDistance += 2*MALUS/(deadlyField+1);
moveBlocked |= !ignorePortals && isPortalEntry && moveDirectionInverse;
if(!moveBlocked && extraIllegalMove && extraIllegalMoveX == xNew && extraIllegalMoveY == yNew){
//Stepping on illegal field
PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, extraIllegalMoveItype, false); //Was passiert mit dem passive?
YoloEvent triggeredEvent = event.getEvent(inventoryItems);
if(triggeredEvent.getMove() || event.getObserveCount() == 0) //Passive bewegt sich?
moveBlocked = true;
}
if(distance[xNew][yNew] == 0 || (interpretedAsWall[xNew][yNew] && !moveBlocked)){
distance[xNew][yNew] = newDistance;
from[xNew][yNew] = (byte)((xNew < x?0:(xNew > x?1:(yNew < y?2:3))));
}
interpretedAsWall[xNew][yNew] = moveBlocked;
//Count appearances:
if(countFoundItypes && deadlyField > 1){
nr = -1;
for (Observation obs : grid[xNew][yNew]) {
nr++;
if(countedObsIds.contains(obs.obsID) || (moveBlocked && !blockedBy[nr] && !useActionEffective[nr]))
continue;
countedObsIds.add(obs.obsID);
int index = YoloKnowledge.instance.itypeToIndex(obs.itype);
if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID))
continue;
int oldVal = iTypesFoundCount[index]++;
if(oldVal == 0){
//Nearest Observation of this itype:
nearestITypeObservationFound[index] = obs;
if(changedItypeX != -1 && changedItypeY != -1){
//Itype has been changed, so move frist to Itypechange!
nearestITypeObservationFoundFirstTargetX[index] = changedItypeX;
nearestITypeObservationFoundFirstTargetY[index] = changedItypeY;
}else{
//Itype has not been changed, move to object
nearestITypeObservationFoundFirstTargetX[index] = xNew;
nearestITypeObservationFoundFirstTargetY[index] = yNew;
}
}
}
}
if(!moveBlocked){
fieldsReachedCount[fromDirection]++;
originDirectionArray[xNew][yNew] = fromDirection;
//Early Stop
if(stopEarly && xNew == stopEarlyX && yNew == stopEarlyY)
return retVal;
boolean teleported = false;
if(portalIType != -1 && !ignorePortals){
int portalExitIType = -1, portalExitIndex;
if(!moveDirectionInverse){
PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, portalIType, true);
YoloEvent event = pEvent.getEvent(inventoryItems);
portalExitIndex = event.getTeleportTo();
if(!pEvent.willCancel(inventoryItems) && portalExitIndex != -1)
portalExitIType = YoloKnowledge.instance.indexToItype(portalExitIndex);
}else{
portalExitIType = portalIType;
portalExitIndex = YoloKnowledge.instance.itypeToIndex(portalExitIType);
}
if(portalExitIType != -1){
int portalExitCategory = YoloKnowledge.instance.getObjectCategory(portalExitIndex, state);
if(portalExitCategory != -1){
ArrayList<Observation>[] obs = state.getObservationList(portalExitCategory);
if(obs != null){
ArrayList<Observation> portalExits = null;
for (ArrayList<Observation> list : obs) {
if(!list.isEmpty() && list.get(0).itype == portalExitIType)
portalExits = list;
}
if(portalExits != null){
//Habe Portalausgaenge gefunden!
teleported = true;
int blockSize = state.getBlockSize();
for (Observation exit : portalExits) {
xNew = (int)exit.position.x/blockSize;
yNew = (int)exit.position.y/blockSize;
if(xNew < 0 || yNew < 0 || xNew >= distance.length ||yNew >= distance[xNew].length)
continue;
if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){
//Hier war die SUche noch nicht!
from[xNew][yNew] = 5;
originDirectionArray[xNew][yNew] = fromDirection;
distance[xNew][yNew] = newDistance;
queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY));
}else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){
//Hier waren wir schon, untersuche zyklus
handleZyklus(fromDirection, originDirectionArray[xNew][yNew]);
}
}
}
}
}
}
}
if(!teleported){
//Standard appending for later loop
queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY));
}
}
}else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){
//Hier waren wir schon, untersuche zyklus
handleZyklus(fromDirection, originDirectionArray[xNew][yNew]);
}
}
}
}
//Postwork - zycles:
for (int iteration = 0; iteration < 2; iteration++) {
for (int from = 0; from < zycleMet.length; from++) {
for (int to = 0; to < 4; to++) {
if(to == from)
continue;
if((zycleMet[from]>>to & 1) == 1){
//from hat zykel zu to
byte newMask = (byte) (zycleMet[from] | zycleMet[to]);
zycleMet[from] = newMask;
zycleMet[to] = newMask;
}
}
}
}
int[] oldFieldReached = new int[]{fieldsReachedCount[0],fieldsReachedCount[1],fieldsReachedCount[2],fieldsReachedCount[3]};
for (int from = 0; from < zycleMet.length; from++) {
fieldsReachedCount[from] = 0;
for (int to = 0; to < 4; to++) {
if((zycleMet[from]>>to & 1) == 1){
//from hat zykel zu to
fieldsReachedCount[from] += oldFieldReached[to];
}
}
}
return retVal;
}
private int canBeKilledAtByStochasticEnemy(int x, int y){
return state.getStochasticKillMap().getMinDistanceToEnemy(x,y);
}
public LinkedList<ACTIONS> extractActions(int xTarget, int yTarget) {
LinkedList<ACTIONS> actionsToDo = new LinkedList<ACTIONS>();
if (distance[xTarget][yTarget] > 1) {
// Weg gefunden(!= 0) und bewegen notwendig(!= 1)
int curX = xTarget;
int curY = yTarget;
while (distance[curX][curY] > 1) {
switch (from[curX][curY]) {
case KnowledgeBasedAStar.BOTTOM:
actionsToDo.addFirst(ACTIONS.ACTION_DOWN);
curY--;
break;
case KnowledgeBasedAStar.TOP:
actionsToDo.addFirst(ACTIONS.ACTION_UP);
curY++;
break;
case KnowledgeBasedAStar.LEFT:
actionsToDo.addFirst(ACTIONS.ACTION_LEFT);
curX++;
break;
case KnowledgeBasedAStar.RIGHT:
actionsToDo.addFirst(ACTIONS.ACTION_RIGHT);
curX--;
break;
default:
//TODO: Portal-Case<SUF>
System.err.println("Portal gefunden, aber 'extractActions' wurde noch nicht passend implementiert!!");
break;
}
}
}
return actionsToDo;
}
public void setIgnoreOneMoveableOfType(int itype) {
oneMoveableIgnoreIType = itype;
}
public void setCountFoundItypes(boolean value) {
this.countFoundItypes = value;
}
public void setMoveDirectionInverse(boolean value) {
moveDirectionInverse = value;
fromAvatarDistance = distance;
}
private void handleZyklus(byte direction1, byte direction2){
zycleMet[direction1] |= 1<<direction2;
}
public void setBlacklistedObjects(Collection<Integer> blacklistedObjects) {
this.blacklistedObjects = blacklistedObjects;
}
}
|
111873_0 | package technion.prime.eclipse.views;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.ViewPart;
import technion.prime.dom.AppClass;
import technion.prime.history.History;
import technion.prime.history.HistoryCollection;
import technion.prime.statistics.Field;
import technion.prime.statistics.AnalysisDetails;
import technion.prime.statistics.Sample;
import technion.prime.utils.Logger;
import technion.prime.utils.Logger.CanceledException;
public class TreeResultsView extends ViewPart {
public static final String ID = "technion.prime.eclipse.views.TreeResultsView";
private static final Field[] sample_columns = new Field[] {
Sample.NAME,
Sample.NUM_SAMPLES,
Sample.PERCENTAGE_SAMPLES,
Sample.SIZE,
Sample.MAX_WEIGHT,
Sample.DEPTH,
Sample.NUM_TYPES,
Sample.NUM_EDGES,
Sample.NUM_UNKNOWN_EDGES
};
private static final Field[] query_columns = new Field[] {
AnalysisDetails.QUERY_STRING,
AnalysisDetails.NUM_SAMPLES,
};
private static final String FILENAME_PROPERTY = "filename";
private static final String SAMPLE_PROPERTY = "sample";
private static final String HISTORY_PROPERTY = "history";
private Clipboard clipboard;
private Tree tree;
private Text statisticsText;
private List uncompilableList;
private List unanalyzableList;
private Action resultLineDoubleClick;
private Action uncompilableDoubleClick;
private Action unanalyzableDoubleClick;
private Action copyAction;
private Action saveAsHtmlAction;
private Action saveAsXmlAction;
private Action saveCachedFileAction;
private TabFolder tabFolder;
private Image image_ascending;
private Image image_descending;
private AnalysisDetails details;
private String filterString = "";
private Field sort_field = sample_columns[1];
private boolean sort_ascending = false;
private Set<Sample> childPassesFilter = new HashSet<Sample>();
private Set<Sample> parentPassesFilter = new HashSet<Sample>();
private int saveCounter = 0;
private String outputFolder;
public void setResults(AnalysisDetails details) {
if (details == null) return;
this.details = details;
// Populate tree:
drawTree();
// Populate statistics:
statisticsText.setText(details.getProcessDetails());
// Populate uncompilable:
for (String s : details.getUncompilableSources()) {
uncompilableList.add(s);
}
// Populate unanalyzable:
for (AppClass c : details.getUnanalyzableClasses()) {
if (c.getClassFileName() == null) continue;
uncompilableList.add(c.getClassFileName());
}
}
private void drawTree() {
if (details == null) return;
Set<Sample> expanded = new HashSet<Sample>();
for (TreeItem ti : tree.getItems()) {
expanded.addAll(getExpanded(ti));
}
boolean wasQueryExpanded = tree.getItemCount() > 0 ? tree.getItem(0).getExpanded() : true;
tree.removeAll();
if (details != null) createTreeItemFromAnalysisDetails(tree, expanded);
TreeItem root = tree.getItems()[0];
//TreeItem root = tree.getTopItem();
if (root != null) root.setExpanded(wasQueryExpanded);
}
private Set<Sample> getExpanded(TreeItem parent) {
Set<Sample> result = new HashSet<Sample>();
if (parent.getExpanded()) result.add((Sample)parent.getData(SAMPLE_PROPERTY));
for (TreeItem ti : parent.getItems()) {
result.addAll(getExpanded(ti));
}
return result;
}
private void createTreeItemFromAnalysisDetails(Tree parent, Set<Sample> toExpand) {
TreeItem ti = new TreeItem(parent, SWT.NONE);
int i = 0;
for (Field f : query_columns) {
ti.setText(i++, f == null ? "" : details.getString(f));
}
Set<Sample> filtered = filter(details.getSamples(), false);
Sample[] sorted = sortSamples(filtered, sort_field, sort_ascending);
for (Sample s : sorted) {
createTreeItemFromSample(ti, s, toExpand);
}
}
private Set<Sample> filter(Set<Sample> samples, boolean parentPassed) {
Set<Sample> result = new HashSet<Sample>();
for (Sample s : samples) {
boolean thisPassed = passesFilter(s);
Set<Sample> filtered = filter(s.getSamples(), parentPassed || thisPassed);
boolean childPassed = filtered.size() > 0;
if (parentPassed) parentPassesFilter.add(s);
if (childPassed) childPassesFilter.add(s);
if (childPassed || thisPassed) result.add(s);
}
return result;
}
private boolean passesFilter(Sample s) {
if (filterString.isEmpty()) return true;
boolean matchesAll = true;
for (String word : filterString.split(" ")) {
matchesAll &= word.toLowerCase().equals(word) ?
// It's all lower-case
s.getString(Sample.NAME).toLowerCase().contains(word.toLowerCase()) :
// At least one upper-case character
s.getString(Sample.NAME).contains(word);
if (matchesAll == false) break;
}
return matchesAll;
}
private void createTreeItemFromSample(TreeItem parent, Sample s, Set<Sample> toExpand) {
TreeItem ti = new TreeItem(parent, SWT.NONE);
boolean directlyPassesFilter = passesFilter(s);
if (!(directlyPassesFilter || childPassesFilter.contains(s) || parentPassesFilter.contains(s))) {
ti.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
}
int i = 0;
boolean skip = false;
for (Field f : sample_columns) {
// Stripe columns:
if (i % 2 == 1) ti.setBackground(i, ti.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
if (f == null || skip) {
ti.setText(i++, "");
skip = false;
continue;
}
if (f == Sample.NUM_SAMPLES && s.getInteger(f) == 0) {
ti.setText(i++, "");
skip = true;
continue;
}
ti.setText(i, s.getString(f));
if (isPoor(f, s) && directlyPassesFilter) {
ti.setForeground(0, parent.getDisplay().getSystemColor(SWT.COLOR_RED));
ti.setForeground(i, parent.getDisplay().getSystemColor(SWT.COLOR_RED));
} else if (isGreat(f, s) && directlyPassesFilter) {
ti.setForeground(i, parent.getDisplay().getSystemColor(SWT.COLOR_BLUE));
}
i++;
}
ti.setData(SAMPLE_PROPERTY, s);
ti.setData(HISTORY_PROPERTY, details.getSampleHistory(s));
Sample[] sorted = sortSamples(s.getSamples(), sort_field, sort_ascending);
for (Sample inner : sorted) {
createTreeItemFromSample(ti, inner, toExpand);
}
if (toExpand.contains(s)) ti.setExpanded(true);
}
private boolean isPoor(Field f, Sample s) {
if (f == Sample.DEPTH) return s.getInteger(f) <= 1;
if (f == Sample.SIZE) return s.getInteger(f) <= 1;
if (f == Sample.NUM_EDGES) return s.getInteger(f) <= 1;
if (f == Sample.NUM_TYPES) return s.getInteger(f) <= 0;
if (f == Sample.MAX_WEIGHT) return s.getDouble(f) <= 0;
if (f == Sample.NUM_SAMPLES) return s.getInteger(f) == 1;
return false;
}
private boolean isGreat(Field f, Sample s) {
if (f == Sample.DEPTH) return s.getInteger(f) >= 5;
if (f == Sample.NUM_SAMPLES) return s.getInteger(f) >= 100;
if (f == Sample.MAX_WEIGHT) return s.getDouble(f) >= 100;
if (f == Sample.PERCENTAGE_SAMPLES) return s.getDouble(f) > 50;
return false;
}
@Override
public void createPartControl(Composite parent) {
clipboard = new Clipboard(parent.getShell().getDisplay());
tabFolder = new TabFolder(parent, SWT.BORDER);
image_ascending = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_FORWARD);
image_descending = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_BACK);
createTreeTab(tabFolder);
createStatisticsTab(tabFolder);
createUncompilableTab(tabFolder);
createUnanalyzableTab(tabFolder);
makeActions();
hookActions();
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(copyAction);
bars.getToolBarManager().add(saveAsHtmlAction);
bars.getToolBarManager().add(saveAsXmlAction);
bars.getToolBarManager().add(saveCachedFileAction);
}
private void createUncompilableTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Uncompilable files");
Control c = createUncompilableList(tabFolder);
tab.setControl(c);
}
private Control createUncompilableList(TabFolder tabFolder) {
uncompilableList = new List(tabFolder, SWT.H_SCROLL | SWT.V_SCROLL);
uncompilableList.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Called on double-click
uncompilableDoubleClick.run();
}
});
return uncompilableList;
}
private void createUnanalyzableTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Unanalyzable classes");
Control c = createUnanalyzableList(tabFolder);
tab.setControl(c);
}
private Control createUnanalyzableList(TabFolder tabFolder) {
unanalyzableList = new List(tabFolder, SWT.H_SCROLL | SWT.V_SCROLL);
unanalyzableList.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Called on double-click
unanalyzableDoubleClick.run();
}
});
return unanalyzableList;
}
private void createTreeTab(TabFolder parent) {
TabItem tab = new TabItem(parent, SWT.NONE);
tab.setText("Results table");
Control table = createTreeArea(tabFolder);
tab.setControl(table);
}
private Control createTreeArea(TabFolder parent) {
Composite c = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(4, false);
c.setLayout(layout);
createSearchBox(c);
createTree(c);
return c;
}
private void createTree(Composite parent) {
tree = new Tree(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE);
tree.setHeaderVisible(true);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 4;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
tree.setLayoutData(gridData);
for (Field f : sample_columns) {
TreeColumn tc = new TreeColumn(tree, SWT.LEFT);
tc.setText(f.getTitle());
tc.setMoveable(true);
tc.setResizable(true);
tc.setWidth(f == Sample.NAME ? 800 : 100);
tc.addSelectionListener(createColumnClickAction(tc, f));
}
tree.addKeyListener(new KeyListener() {
@Override public void keyReleased(KeyEvent e) {
if (tree.getSelectionCount() == 1) {
switch (e.keyCode) {
case SWT.ARROW_RIGHT: tree.getSelection()[0].setExpanded(true); break;
case SWT.ARROW_LEFT: tree.getSelection()[0].setExpanded(false); break;
}
}
}
@Override public void keyPressed(KeyEvent e) {}
});
}
private SelectionListener createColumnClickAction(final TreeColumn tc, final Field f) {
return new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
sort_ascending = sort_field == f ? !sort_ascending : false;
sort_field = f;
for (TreeColumn tc : tree.getColumns()) {
tc.setImage(null);
}
Image image = sort_ascending ? image_ascending : image_descending;
tc.setImage(image);
drawTree();
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
};
}
private Sample[] sortSamples(Set<Sample> samples, final Field f, final boolean ascending) {
Comparator<Sample> comp = new Comparator<Sample>() {
@Override public int compare(Sample s1, Sample s2) {
int order;
if (f.getType() == String.class) {
String string1 = s1.getString(f);
String string2 = s2.getString(f);
if (sharePrefixBeforeNumber(string1, string2)) {
order = compareSuffixNumber(string1, string2);
} else {
order = string1.compareTo(string2);
}
} else {
order = (int)Math.signum(s1.getDouble(f) - s2.getDouble(f));
}
return ascending ? order : -order;
}
};
Sample[] result = samples.toArray(new Sample[samples.size()]);
Arrays.sort(result, comp);
return result;
}
private String getPrefixBeforeNumber(String s) {
Pattern p = Pattern.compile("[^0-9]*");
Matcher m = p.matcher(s);
return m.group();
}
protected int compareSuffixNumber(String string1, String string2) {
string1 = string1.substring(getPrefixBeforeNumber(string1).length());
string2 = string2.substring(getPrefixBeforeNumber(string2).length());
return Double.compare(Double.parseDouble(string1), Double.parseDouble(string2));
}
protected boolean sharePrefixBeforeNumber(String s1, String s2) {
return getPrefixBeforeNumber(s1).equals(getPrefixBeforeNumber(s2));
}
private void createStatisticsTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Statistics");
Control statistics = createStatistics(tabFolder);
tab.setControl(statistics);
}
private Control createStatistics(Composite parent) {
statisticsText = new Text(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
return statisticsText;
}
private void createSearchBox(Composite parent) {
Label searchLabel = new Label(parent, SWT.NONE);
searchLabel.setText("Filter: ");
final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
final Button searchButton = new Button(parent, SWT.NONE);
searchButton.setText("Apply");
searchButton.addSelectionListener(new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
filterString = searchText.getText();
childPassesFilter.clear();
parentPassesFilter.clear();
searchText.selectAll();
drawTree();
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
});
final Button clearButton = new Button(parent, SWT.NONE);
clearButton.setText("Clear");
clearButton.addSelectionListener(new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
searchText.setText("");
searchButton.notifyListeners(SWT.Selection, new Event());
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
});
searchText.addKeyListener(new KeyListener() {
@Override public void keyReleased(KeyEvent e) {
switch (e.keyCode) {
case SWT.CR: searchButton.notifyListeners(SWT.Selection, new Event()); break;
case SWT.ESC: clearButton.notifyListeners(SWT.Selection, new Event()); break;
}
}
@Override public void keyPressed(KeyEvent e) {}
});
}
private void makeActions() {
makeResultLineDoubleClickAction();
makeUncompilableDoubleClickAction();
makeUnanalyzableDoubleClickAction();
makeCopyAction();
makeSaveAsHtmlAction();
makeSaveAsXmlAction();
makeSaveCacheFileAction();
}
private void makeSaveAsXmlAction() {
saveAsXmlAction = new Action() {
@Override
public void run() {
if (details == null) return;
DirectoryDialog dd = new DirectoryDialog(tree.getShell());
String folder = dd.open();
if (folder == null) return;
try {
Logger.log("Generating XML output...");
HistoryCollection hc = details.getFinalHistoryCollection();
hc.generateXmlOutput(folder);
Logger.log("Done.");
} catch (InterruptedException e) {
Logger.exception(e);
} catch (CanceledException e) {
Logger.exception(e);
} catch (IOException e) {
Logger.exception(e);
}
}
};
saveAsXmlAction.setToolTipText("Save each clustered sample as XML file.");
saveAsXmlAction.setText("Save As XML...");
}
private void makeSaveCacheFileAction() {
saveCachedFileAction = new Action() {
@Override
public void run() {
if (details == null) return;
FileDialog fd = new FileDialog(tree.getShell(), SWT.SAVE);
String filepath = fd.open();
if (filepath == null) return;
try {
// This would probably crash if the cs was not the one actually used for clustering:
details.getFinalHistoryCollection().save(filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
};
saveCachedFileAction.setToolTipText("Save the final result to a cached file.");
saveCachedFileAction.setText("Save cache file...");
}
private void makeSaveAsHtmlAction() {
saveAsHtmlAction = new Action() {
@Override
public void run() {
if (details == null) return;
MessageDialog.openError(tree.getShell(), "Unsupported operation",
"This functionality is currently disabled.");
DirectoryDialog dd = new DirectoryDialog(tree.getShell());
String folder = dd.open();
if (folder != null) folder = null;
if (folder == null) return;
@SuppressWarnings("unused")
String filename = "index.xhtml";
try {
Logger.log("Generating HTML and SVG output...");
details.saveToHtml(folder, filename);
Logger.log("Done.");
} catch (IllegalStateException e) {
MessageDialog.openInformation(tree.getShell(), "Could not find dot.exe", e.getMessage());
} catch (IOException e) {
Logger.exception(e);
}
}
};
saveAsHtmlAction.setToolTipText("Save tree with images to an html file.");
saveAsHtmlAction.setText("Save As HTML...");
}
private void makeCopyAction() {
copyAction = new Action() {
@Override
public void run() {
String toCopy = null;
switch (tabFolder.getSelectionIndex()) {
case 0:
StringBuilder sb = new StringBuilder();
for (TreeItem ti : tree.getSelection()) {
Object filename = ti.getData(FILENAME_PROPERTY);
if (filename != null) sb.append(filename.toString());
else sb.append(ti.getText(0));
}
if (sb.length() > 0) toCopy = sb.toString();
case 2:
String[] s1 = uncompilableList.getSelection();
if (s1.length > 0) toCopy = s1[0];
break;
case 3:
String[] s2 = unanalyzableList.getSelection();
if (s2.length > 0) toCopy = s2[0];
break;
}
if (toCopy != null) copyToClipboard(toCopy);
}
};
copyAction.setToolTipText("Copy text from selection to clipboard.");
copyAction.setText("Copy to clipboard");
}
private void makeUnanalyzableDoubleClickAction() {
unanalyzableDoubleClick = new Action() {
@Override
public void run() {
String[] selection = unanalyzableList.getSelection();
if (selection.length > 0) {
String filename = (String)unanalyzableList.getData(selection[0]);
openFile(filename);
}
}
};
}
private void makeUncompilableDoubleClickAction() {
uncompilableDoubleClick = new Action() {
@Override
public void run() {
String[] selection = uncompilableList.getSelection();
if (selection.length > 0) {
openFile(selection[0]);
}
}
};
}
private void makeResultLineDoubleClickAction() {
resultLineDoubleClick = new Action() {
@Override
public void run() {
String filename = getResultSelectionFile();
if (filename != null) openFile(filename);
}
};
}
private String getResultSelectionFile() {
TreeItem[] selection = tree.getSelection();
if (selection.length != 1) return null;
if (selection[0] == tree.getItem(0)) {
// First line - use this for expanding / collapsing all
toggleExpandAll();
return null;
}
Object filename = selection[0].getData(FILENAME_PROPERTY);
if (filename == null) {
History h = (History)selection[0].getData(HISTORY_PROPERTY);
try {
filename = h.generateGraphvizOutput(outputFolder, saveCounter++);
selection[0].setData(FILENAME_PROPERTY, filename);
} catch (IOException e) {
MessageDialog.openError(tree.getShell(), "Output generation saved",
e.getMessage());
} catch (InterruptedException e) {
MessageDialog.openError(tree.getShell(), "Interrupted during saving",
e.getMessage());
} catch (CanceledException e) {
// Cancellation means quickly and silently stopping.
}
}
return filename.toString();
}
private void toggleExpandAll() {
boolean changeTo = ! tree.getItem(0).getExpanded();
toggleExpand(tree.getItem(0), changeTo);
}
private void toggleExpand(TreeItem item, boolean changeTo) {
item.setExpanded(changeTo);
for (TreeItem child : item.getItems()) {
toggleExpand(child, changeTo);
}
}
protected void copyToClipboard(String s) {
clipboard.setContents(new Object[]{s}, new Transfer[] {TextTransfer.getInstance()});
}
private void openFile(String filename) {
if (filename.isEmpty()) {
MessageDialog.openInformation(tree.getShell(), "No file available",
"There was an internal error, no file is available.");
return;
}
File fileToOpen = new File(filename);
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e) {
Logger.exception(e);
}
}
private void hookActions() {
tree.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
resultLineDoubleClick.run();
}
});
}
@Override
public void setFocus() {
tree.setFocus();
}
public void setOutputFolder(String outputFolder) {
this.outputFolder = outputFolder;
}
}
| tech-srl/prime | Prime/src/technion/prime/eclipse/views/TreeResultsView.java | 7,811 | //TreeItem root = tree.getTopItem();
| line_comment | nl | package technion.prime.eclipse.views;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.ViewPart;
import technion.prime.dom.AppClass;
import technion.prime.history.History;
import technion.prime.history.HistoryCollection;
import technion.prime.statistics.Field;
import technion.prime.statistics.AnalysisDetails;
import technion.prime.statistics.Sample;
import technion.prime.utils.Logger;
import technion.prime.utils.Logger.CanceledException;
public class TreeResultsView extends ViewPart {
public static final String ID = "technion.prime.eclipse.views.TreeResultsView";
private static final Field[] sample_columns = new Field[] {
Sample.NAME,
Sample.NUM_SAMPLES,
Sample.PERCENTAGE_SAMPLES,
Sample.SIZE,
Sample.MAX_WEIGHT,
Sample.DEPTH,
Sample.NUM_TYPES,
Sample.NUM_EDGES,
Sample.NUM_UNKNOWN_EDGES
};
private static final Field[] query_columns = new Field[] {
AnalysisDetails.QUERY_STRING,
AnalysisDetails.NUM_SAMPLES,
};
private static final String FILENAME_PROPERTY = "filename";
private static final String SAMPLE_PROPERTY = "sample";
private static final String HISTORY_PROPERTY = "history";
private Clipboard clipboard;
private Tree tree;
private Text statisticsText;
private List uncompilableList;
private List unanalyzableList;
private Action resultLineDoubleClick;
private Action uncompilableDoubleClick;
private Action unanalyzableDoubleClick;
private Action copyAction;
private Action saveAsHtmlAction;
private Action saveAsXmlAction;
private Action saveCachedFileAction;
private TabFolder tabFolder;
private Image image_ascending;
private Image image_descending;
private AnalysisDetails details;
private String filterString = "";
private Field sort_field = sample_columns[1];
private boolean sort_ascending = false;
private Set<Sample> childPassesFilter = new HashSet<Sample>();
private Set<Sample> parentPassesFilter = new HashSet<Sample>();
private int saveCounter = 0;
private String outputFolder;
public void setResults(AnalysisDetails details) {
if (details == null) return;
this.details = details;
// Populate tree:
drawTree();
// Populate statistics:
statisticsText.setText(details.getProcessDetails());
// Populate uncompilable:
for (String s : details.getUncompilableSources()) {
uncompilableList.add(s);
}
// Populate unanalyzable:
for (AppClass c : details.getUnanalyzableClasses()) {
if (c.getClassFileName() == null) continue;
uncompilableList.add(c.getClassFileName());
}
}
private void drawTree() {
if (details == null) return;
Set<Sample> expanded = new HashSet<Sample>();
for (TreeItem ti : tree.getItems()) {
expanded.addAll(getExpanded(ti));
}
boolean wasQueryExpanded = tree.getItemCount() > 0 ? tree.getItem(0).getExpanded() : true;
tree.removeAll();
if (details != null) createTreeItemFromAnalysisDetails(tree, expanded);
TreeItem root = tree.getItems()[0];
//TreeItem root<SUF>
if (root != null) root.setExpanded(wasQueryExpanded);
}
private Set<Sample> getExpanded(TreeItem parent) {
Set<Sample> result = new HashSet<Sample>();
if (parent.getExpanded()) result.add((Sample)parent.getData(SAMPLE_PROPERTY));
for (TreeItem ti : parent.getItems()) {
result.addAll(getExpanded(ti));
}
return result;
}
private void createTreeItemFromAnalysisDetails(Tree parent, Set<Sample> toExpand) {
TreeItem ti = new TreeItem(parent, SWT.NONE);
int i = 0;
for (Field f : query_columns) {
ti.setText(i++, f == null ? "" : details.getString(f));
}
Set<Sample> filtered = filter(details.getSamples(), false);
Sample[] sorted = sortSamples(filtered, sort_field, sort_ascending);
for (Sample s : sorted) {
createTreeItemFromSample(ti, s, toExpand);
}
}
private Set<Sample> filter(Set<Sample> samples, boolean parentPassed) {
Set<Sample> result = new HashSet<Sample>();
for (Sample s : samples) {
boolean thisPassed = passesFilter(s);
Set<Sample> filtered = filter(s.getSamples(), parentPassed || thisPassed);
boolean childPassed = filtered.size() > 0;
if (parentPassed) parentPassesFilter.add(s);
if (childPassed) childPassesFilter.add(s);
if (childPassed || thisPassed) result.add(s);
}
return result;
}
private boolean passesFilter(Sample s) {
if (filterString.isEmpty()) return true;
boolean matchesAll = true;
for (String word : filterString.split(" ")) {
matchesAll &= word.toLowerCase().equals(word) ?
// It's all lower-case
s.getString(Sample.NAME).toLowerCase().contains(word.toLowerCase()) :
// At least one upper-case character
s.getString(Sample.NAME).contains(word);
if (matchesAll == false) break;
}
return matchesAll;
}
private void createTreeItemFromSample(TreeItem parent, Sample s, Set<Sample> toExpand) {
TreeItem ti = new TreeItem(parent, SWT.NONE);
boolean directlyPassesFilter = passesFilter(s);
if (!(directlyPassesFilter || childPassesFilter.contains(s) || parentPassesFilter.contains(s))) {
ti.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
}
int i = 0;
boolean skip = false;
for (Field f : sample_columns) {
// Stripe columns:
if (i % 2 == 1) ti.setBackground(i, ti.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
if (f == null || skip) {
ti.setText(i++, "");
skip = false;
continue;
}
if (f == Sample.NUM_SAMPLES && s.getInteger(f) == 0) {
ti.setText(i++, "");
skip = true;
continue;
}
ti.setText(i, s.getString(f));
if (isPoor(f, s) && directlyPassesFilter) {
ti.setForeground(0, parent.getDisplay().getSystemColor(SWT.COLOR_RED));
ti.setForeground(i, parent.getDisplay().getSystemColor(SWT.COLOR_RED));
} else if (isGreat(f, s) && directlyPassesFilter) {
ti.setForeground(i, parent.getDisplay().getSystemColor(SWT.COLOR_BLUE));
}
i++;
}
ti.setData(SAMPLE_PROPERTY, s);
ti.setData(HISTORY_PROPERTY, details.getSampleHistory(s));
Sample[] sorted = sortSamples(s.getSamples(), sort_field, sort_ascending);
for (Sample inner : sorted) {
createTreeItemFromSample(ti, inner, toExpand);
}
if (toExpand.contains(s)) ti.setExpanded(true);
}
private boolean isPoor(Field f, Sample s) {
if (f == Sample.DEPTH) return s.getInteger(f) <= 1;
if (f == Sample.SIZE) return s.getInteger(f) <= 1;
if (f == Sample.NUM_EDGES) return s.getInteger(f) <= 1;
if (f == Sample.NUM_TYPES) return s.getInteger(f) <= 0;
if (f == Sample.MAX_WEIGHT) return s.getDouble(f) <= 0;
if (f == Sample.NUM_SAMPLES) return s.getInteger(f) == 1;
return false;
}
private boolean isGreat(Field f, Sample s) {
if (f == Sample.DEPTH) return s.getInteger(f) >= 5;
if (f == Sample.NUM_SAMPLES) return s.getInteger(f) >= 100;
if (f == Sample.MAX_WEIGHT) return s.getDouble(f) >= 100;
if (f == Sample.PERCENTAGE_SAMPLES) return s.getDouble(f) > 50;
return false;
}
@Override
public void createPartControl(Composite parent) {
clipboard = new Clipboard(parent.getShell().getDisplay());
tabFolder = new TabFolder(parent, SWT.BORDER);
image_ascending = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_FORWARD);
image_descending = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_BACK);
createTreeTab(tabFolder);
createStatisticsTab(tabFolder);
createUncompilableTab(tabFolder);
createUnanalyzableTab(tabFolder);
makeActions();
hookActions();
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(copyAction);
bars.getToolBarManager().add(saveAsHtmlAction);
bars.getToolBarManager().add(saveAsXmlAction);
bars.getToolBarManager().add(saveCachedFileAction);
}
private void createUncompilableTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Uncompilable files");
Control c = createUncompilableList(tabFolder);
tab.setControl(c);
}
private Control createUncompilableList(TabFolder tabFolder) {
uncompilableList = new List(tabFolder, SWT.H_SCROLL | SWT.V_SCROLL);
uncompilableList.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Called on double-click
uncompilableDoubleClick.run();
}
});
return uncompilableList;
}
private void createUnanalyzableTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Unanalyzable classes");
Control c = createUnanalyzableList(tabFolder);
tab.setControl(c);
}
private Control createUnanalyzableList(TabFolder tabFolder) {
unanalyzableList = new List(tabFolder, SWT.H_SCROLL | SWT.V_SCROLL);
unanalyzableList.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Called on double-click
unanalyzableDoubleClick.run();
}
});
return unanalyzableList;
}
private void createTreeTab(TabFolder parent) {
TabItem tab = new TabItem(parent, SWT.NONE);
tab.setText("Results table");
Control table = createTreeArea(tabFolder);
tab.setControl(table);
}
private Control createTreeArea(TabFolder parent) {
Composite c = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(4, false);
c.setLayout(layout);
createSearchBox(c);
createTree(c);
return c;
}
private void createTree(Composite parent) {
tree = new Tree(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE);
tree.setHeaderVisible(true);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 4;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
tree.setLayoutData(gridData);
for (Field f : sample_columns) {
TreeColumn tc = new TreeColumn(tree, SWT.LEFT);
tc.setText(f.getTitle());
tc.setMoveable(true);
tc.setResizable(true);
tc.setWidth(f == Sample.NAME ? 800 : 100);
tc.addSelectionListener(createColumnClickAction(tc, f));
}
tree.addKeyListener(new KeyListener() {
@Override public void keyReleased(KeyEvent e) {
if (tree.getSelectionCount() == 1) {
switch (e.keyCode) {
case SWT.ARROW_RIGHT: tree.getSelection()[0].setExpanded(true); break;
case SWT.ARROW_LEFT: tree.getSelection()[0].setExpanded(false); break;
}
}
}
@Override public void keyPressed(KeyEvent e) {}
});
}
private SelectionListener createColumnClickAction(final TreeColumn tc, final Field f) {
return new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
sort_ascending = sort_field == f ? !sort_ascending : false;
sort_field = f;
for (TreeColumn tc : tree.getColumns()) {
tc.setImage(null);
}
Image image = sort_ascending ? image_ascending : image_descending;
tc.setImage(image);
drawTree();
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
};
}
private Sample[] sortSamples(Set<Sample> samples, final Field f, final boolean ascending) {
Comparator<Sample> comp = new Comparator<Sample>() {
@Override public int compare(Sample s1, Sample s2) {
int order;
if (f.getType() == String.class) {
String string1 = s1.getString(f);
String string2 = s2.getString(f);
if (sharePrefixBeforeNumber(string1, string2)) {
order = compareSuffixNumber(string1, string2);
} else {
order = string1.compareTo(string2);
}
} else {
order = (int)Math.signum(s1.getDouble(f) - s2.getDouble(f));
}
return ascending ? order : -order;
}
};
Sample[] result = samples.toArray(new Sample[samples.size()]);
Arrays.sort(result, comp);
return result;
}
private String getPrefixBeforeNumber(String s) {
Pattern p = Pattern.compile("[^0-9]*");
Matcher m = p.matcher(s);
return m.group();
}
protected int compareSuffixNumber(String string1, String string2) {
string1 = string1.substring(getPrefixBeforeNumber(string1).length());
string2 = string2.substring(getPrefixBeforeNumber(string2).length());
return Double.compare(Double.parseDouble(string1), Double.parseDouble(string2));
}
protected boolean sharePrefixBeforeNumber(String s1, String s2) {
return getPrefixBeforeNumber(s1).equals(getPrefixBeforeNumber(s2));
}
private void createStatisticsTab(TabFolder tabFolder) {
TabItem tab = new TabItem(tabFolder, SWT.NONE);
tab.setText("Statistics");
Control statistics = createStatistics(tabFolder);
tab.setControl(statistics);
}
private Control createStatistics(Composite parent) {
statisticsText = new Text(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
return statisticsText;
}
private void createSearchBox(Composite parent) {
Label searchLabel = new Label(parent, SWT.NONE);
searchLabel.setText("Filter: ");
final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
final Button searchButton = new Button(parent, SWT.NONE);
searchButton.setText("Apply");
searchButton.addSelectionListener(new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
filterString = searchText.getText();
childPassesFilter.clear();
parentPassesFilter.clear();
searchText.selectAll();
drawTree();
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
});
final Button clearButton = new Button(parent, SWT.NONE);
clearButton.setText("Clear");
clearButton.addSelectionListener(new SelectionListener() {
@Override public void widgetSelected(SelectionEvent e) {
searchText.setText("");
searchButton.notifyListeners(SWT.Selection, new Event());
}
@Override public void widgetDefaultSelected(SelectionEvent e) {}
});
searchText.addKeyListener(new KeyListener() {
@Override public void keyReleased(KeyEvent e) {
switch (e.keyCode) {
case SWT.CR: searchButton.notifyListeners(SWT.Selection, new Event()); break;
case SWT.ESC: clearButton.notifyListeners(SWT.Selection, new Event()); break;
}
}
@Override public void keyPressed(KeyEvent e) {}
});
}
private void makeActions() {
makeResultLineDoubleClickAction();
makeUncompilableDoubleClickAction();
makeUnanalyzableDoubleClickAction();
makeCopyAction();
makeSaveAsHtmlAction();
makeSaveAsXmlAction();
makeSaveCacheFileAction();
}
private void makeSaveAsXmlAction() {
saveAsXmlAction = new Action() {
@Override
public void run() {
if (details == null) return;
DirectoryDialog dd = new DirectoryDialog(tree.getShell());
String folder = dd.open();
if (folder == null) return;
try {
Logger.log("Generating XML output...");
HistoryCollection hc = details.getFinalHistoryCollection();
hc.generateXmlOutput(folder);
Logger.log("Done.");
} catch (InterruptedException e) {
Logger.exception(e);
} catch (CanceledException e) {
Logger.exception(e);
} catch (IOException e) {
Logger.exception(e);
}
}
};
saveAsXmlAction.setToolTipText("Save each clustered sample as XML file.");
saveAsXmlAction.setText("Save As XML...");
}
private void makeSaveCacheFileAction() {
saveCachedFileAction = new Action() {
@Override
public void run() {
if (details == null) return;
FileDialog fd = new FileDialog(tree.getShell(), SWT.SAVE);
String filepath = fd.open();
if (filepath == null) return;
try {
// This would probably crash if the cs was not the one actually used for clustering:
details.getFinalHistoryCollection().save(filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
};
saveCachedFileAction.setToolTipText("Save the final result to a cached file.");
saveCachedFileAction.setText("Save cache file...");
}
private void makeSaveAsHtmlAction() {
saveAsHtmlAction = new Action() {
@Override
public void run() {
if (details == null) return;
MessageDialog.openError(tree.getShell(), "Unsupported operation",
"This functionality is currently disabled.");
DirectoryDialog dd = new DirectoryDialog(tree.getShell());
String folder = dd.open();
if (folder != null) folder = null;
if (folder == null) return;
@SuppressWarnings("unused")
String filename = "index.xhtml";
try {
Logger.log("Generating HTML and SVG output...");
details.saveToHtml(folder, filename);
Logger.log("Done.");
} catch (IllegalStateException e) {
MessageDialog.openInformation(tree.getShell(), "Could not find dot.exe", e.getMessage());
} catch (IOException e) {
Logger.exception(e);
}
}
};
saveAsHtmlAction.setToolTipText("Save tree with images to an html file.");
saveAsHtmlAction.setText("Save As HTML...");
}
private void makeCopyAction() {
copyAction = new Action() {
@Override
public void run() {
String toCopy = null;
switch (tabFolder.getSelectionIndex()) {
case 0:
StringBuilder sb = new StringBuilder();
for (TreeItem ti : tree.getSelection()) {
Object filename = ti.getData(FILENAME_PROPERTY);
if (filename != null) sb.append(filename.toString());
else sb.append(ti.getText(0));
}
if (sb.length() > 0) toCopy = sb.toString();
case 2:
String[] s1 = uncompilableList.getSelection();
if (s1.length > 0) toCopy = s1[0];
break;
case 3:
String[] s2 = unanalyzableList.getSelection();
if (s2.length > 0) toCopy = s2[0];
break;
}
if (toCopy != null) copyToClipboard(toCopy);
}
};
copyAction.setToolTipText("Copy text from selection to clipboard.");
copyAction.setText("Copy to clipboard");
}
private void makeUnanalyzableDoubleClickAction() {
unanalyzableDoubleClick = new Action() {
@Override
public void run() {
String[] selection = unanalyzableList.getSelection();
if (selection.length > 0) {
String filename = (String)unanalyzableList.getData(selection[0]);
openFile(filename);
}
}
};
}
private void makeUncompilableDoubleClickAction() {
uncompilableDoubleClick = new Action() {
@Override
public void run() {
String[] selection = uncompilableList.getSelection();
if (selection.length > 0) {
openFile(selection[0]);
}
}
};
}
private void makeResultLineDoubleClickAction() {
resultLineDoubleClick = new Action() {
@Override
public void run() {
String filename = getResultSelectionFile();
if (filename != null) openFile(filename);
}
};
}
private String getResultSelectionFile() {
TreeItem[] selection = tree.getSelection();
if (selection.length != 1) return null;
if (selection[0] == tree.getItem(0)) {
// First line - use this for expanding / collapsing all
toggleExpandAll();
return null;
}
Object filename = selection[0].getData(FILENAME_PROPERTY);
if (filename == null) {
History h = (History)selection[0].getData(HISTORY_PROPERTY);
try {
filename = h.generateGraphvizOutput(outputFolder, saveCounter++);
selection[0].setData(FILENAME_PROPERTY, filename);
} catch (IOException e) {
MessageDialog.openError(tree.getShell(), "Output generation saved",
e.getMessage());
} catch (InterruptedException e) {
MessageDialog.openError(tree.getShell(), "Interrupted during saving",
e.getMessage());
} catch (CanceledException e) {
// Cancellation means quickly and silently stopping.
}
}
return filename.toString();
}
private void toggleExpandAll() {
boolean changeTo = ! tree.getItem(0).getExpanded();
toggleExpand(tree.getItem(0), changeTo);
}
private void toggleExpand(TreeItem item, boolean changeTo) {
item.setExpanded(changeTo);
for (TreeItem child : item.getItems()) {
toggleExpand(child, changeTo);
}
}
protected void copyToClipboard(String s) {
clipboard.setContents(new Object[]{s}, new Transfer[] {TextTransfer.getInstance()});
}
private void openFile(String filename) {
if (filename.isEmpty()) {
MessageDialog.openInformation(tree.getShell(), "No file available",
"There was an internal error, no file is available.");
return;
}
File fileToOpen = new File(filename);
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e) {
Logger.exception(e);
}
}
private void hookActions() {
tree.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
resultLineDoubleClick.run();
}
});
}
@Override
public void setFocus() {
tree.setFocus();
}
public void setOutputFolder(String outputFolder) {
this.outputFolder = outputFolder;
}
}
|
84284_48 | package com.example.treasurehunt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
/*
* The quiz level
*
* @author group 8
*/
public class Quiz extends Activity {
/*
* Properties
*/
private TableLayout map;
private Cell cells[][];
private int numberOfRows = 0;
private int numberOfColumns = 0;
private int totalTraps = 0;
private int level = 1;
private int lives = 0;
private int totalScore = 0;
private int step = 0;
private int cellWidth = 34;
private int cellPadding = 2;
// Tracking time
private Handler clock;
private int timer;
private boolean isQuizOver;
private boolean isQuizStart;
// Texts
Typeface font;
TextView levelText, scoreText, timeText, livesText, finalScoreText,
finalTimeText;;
// UI
ImageView mImgViewResult;
// Save Score
private SharedPreferences QuizPrefs;
public static final String Quiz_PREFS = "ArithmeticFile";
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_root);
Options option = new Options();
option.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.gamebg, option);
if (bmp != null) {
layout.setBackgroundDrawable(new BitmapDrawable(getResources(), bmp));
}
map = (TableLayout) findViewById(R.id.Map);
try {
Bundle extras = getIntent().getExtras();
if (extras != null) {
String val1 = extras.getString("Level");
level = Integer.parseInt(val1);
val1 = extras.getString("Total Score");
totalScore = Integer.parseInt(val1);
val1 = extras.getString("Lives");
lives = Integer.parseInt(val1);
} else {
Toast.makeText(this, "Cannot load the game", Toast.LENGTH_SHORT)
.show();
Intent backToMainMenu = new Intent(Quiz.this, MainMenu.class);
startActivity(backToMainMenu);
}
} catch (Exception e) {
Toast.makeText(this, "Cannot load the game", Toast.LENGTH_SHORT)
.show();
Intent backToMainMenu = new Intent(Quiz.this, MainMenu.class);
startActivity(backToMainMenu);
}
initView();
quizControl(level);
startQuizGame();
}
/*
* Initial view
*
* @author 8A Tran Trong Viet
*/
private void initView() {
font = Typeface.createFromAsset(getBaseContext().getAssets(),
"fonts/FRANCHISE-BOLD.TTF");
levelText = (TextView) findViewById(R.id.levelText);
levelText.setTypeface(font);
scoreText = (TextView) findViewById(R.id.scoreText);
scoreText.setTypeface(font);
timeText = (TextView) findViewById(R.id.timeText);
timeText.setTypeface(font);
livesText = (TextView) findViewById(R.id.livesText);
livesText.setTypeface(font);
levelText.setText("Quiz " + level);
scoreText.setText("" + totalScore);
livesText.setText("" + lives);
mImgViewResult = (ImageView) findViewById(R.id.img_result);
numberOfRows = 16;
numberOfColumns = 30;
clock = new Handler();
}
private void quizControl(int _level) {
switch (_level) {
case 5:
setUpQuiz(300, 60);
break;
case 10:
setUpQuiz(300, 90);
break;
default:
break;
}
}
/*
* Set up the Quiz properties
*
* @author 8A Tran Trong Viet
*
* @param playTime the time of current level
*
* @numberOfTraps the number of traps in current level
*
* @score the current score
*
* @_lives the current lives
*/
private void setUpQuiz(int playTime, int numberOfTraps) {
totalTraps = numberOfTraps;
timer = playTime;
}
/*
* Start the Quiz
*
* @author 8A Tran Trong Viet
*/
private void startQuizGame() {
createMap();
showMap();
isQuizOver = false;
isQuizStart = false;
timeText.setText("" + timer);
genMap();
}
/*
* Create new map
*
* @author 8A Tran Trong Viet
*/
protected void createMap() {
// We make more 2 row and column, the 0 row/column and the last one are
// not showed
cells = new Cell[numberOfRows + 2][numberOfColumns + 2];
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
cells[row][column] = new Cell(this);
cells[row][column].setDefaults();
final int currentRow = row;
final int currentColumn = column;
cells[row][column].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
onClickOnCellHandle(currentRow, currentColumn);
}
});
}
}
}
/*
* This method handles the on click event
*
* @author 8A Tran Trong Viet
*
* @param currentRow the position of the clicked cell
*
* @param currentCol the position of the clicked cell
*/
private void onClickOnCellHandle(int currentRow, int currentColumn) {
if (!isQuizStart) {
startTimer();
isQuizStart = true;
}
if (cells[currentRow][currentColumn].isCovered()) {
rippleUncover(currentRow, currentColumn);
if (cells[currentRow][currentColumn].hasTrap()) {
cells[currentRow][currentColumn].OpenCell();
finishGame(currentRow, currentColumn);
} else {
step++;
}
if (checkGameWin(cells[currentRow][currentColumn])) {
winGame();
}
}
}
/*
* Check the game wins or not (should do this for changing rules)
*
* @author 8A Tran Trong Viet
*
* @param cell the cell which is clicked
*/
private boolean checkGameWin(Cell cell) {
return step == 10;
}
/*
* finish the game
*
* @author 8A Tran Trong Viet
*/
private void finishGame(int currentRow, int currentColumn) {
stopTimer(); // stop timer
isQuizStart = false;
// show all traps
// disable all traps
for (int row = 1; row < numberOfRows + 1; row++) {
for (int column = 1; column < numberOfColumns + 1; column++) {
// disable block
// cells[row][column].setCellAsDisabled(false);
cells[row][column].disableCell();
}
}
// trigger trap
cells[currentRow][currentColumn].triggerTrap();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setBackgroundResource(R.drawable.trapped);
mImgViewResult.setVisibility(View.VISIBLE);
mImgViewResult.bringToFront();
mImgViewResult.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setVisibility(View.GONE);
if (!isQuizOver) {
isQuizOver = true; // mark game as over
final Dialog popup = new Dialog(Quiz.this);
popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
popup.getWindow()
.setBackgroundDrawable(
new ColorDrawable(
android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.win_popup);
popup.setCancelable(false);
finalScoreText = (TextView) popup
.findViewById(R.id.finalScore);
finalScoreText.setTypeface(font);
finalScoreText.setText("" + totalScore);
finalTimeText = (TextView) popup
.findViewById(R.id.finalTime);
finalTimeText.setTypeface(font);
finalTimeText.setText("" + timer);
popup.show();
Button saveRecordBtn = (Button) popup
.findViewById(R.id.save_record);
saveRecordBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alert = new AlertDialog.Builder(
Quiz.this);
alert.setTitle("Enter your name");
// Set an EditText view to get user
// input
final EditText input = new EditText(
Quiz.this);
alert.setView(input);
alert.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
String value = input
.getText()
.toString();
// Do something with
// value!
setHighScore(value,
totalScore,
level);
popup.dismiss();
}
});
alert.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
Button quitToMenuBtn = (Button) popup
.findViewById(R.id.quit_to_menu);
quitToMenuBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent backToMenu = new Intent(
Quiz.this, MainMenu.class);
startActivity(backToMenu);
}
});
Button nextLevelBtn = (Button) popup
.findViewById(R.id.next_level);
nextLevelBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
level++;
Intent nextLevel = new Intent(
Quiz.this, Game.class);
nextLevel.putExtra("Level", ""
+ level);
nextLevel.putExtra("Total Score",
"" + totalScore);
nextLevel.putExtra("Lives", ""
+ lives);
startActivity(nextLevel);
finish();
}
});
Button postToFbBtn = (Button) popup
.findViewById(R.id.post_to_fb);
postToFbBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
}, 2000);
}
}, 500);
}
/*
* Win the game
*
* @author 8A Tran Trong Viet
*/
private void winGame() {
// reset all stuffs
stopTimer();
isQuizStart = false;
totalScore += 500;
// disable all buttons
// set flagged all un-flagged blocks
for (int row = 1; row < numberOfRows + 1; row++) {
for (int column = 1; column < numberOfColumns + 1; column++) {
cells[row][column].setClickable(false);
if (cells[row][column].hasTrap()) {
cells[row][column].setTrapIcon(true);
}
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setBackgroundResource(R.drawable.congrat);
mImgViewResult.setVisibility(View.VISIBLE);
mImgViewResult.bringToFront();
mImgViewResult.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setVisibility(View.GONE);
if (!isQuizOver) {
isQuizOver = true; // mark game as over
final Dialog popup = new Dialog(Quiz.this);
popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
popup.getWindow()
.setBackgroundDrawable(
new ColorDrawable(
android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.win_popup);
popup.setCancelable(false);
finalScoreText = (TextView) popup
.findViewById(R.id.finalScore);
finalScoreText.setTypeface(font);
finalScoreText.setText("" + totalScore);
finalTimeText = (TextView) popup
.findViewById(R.id.finalTime);
finalTimeText.setTypeface(font);
finalTimeText.setText("" + timer);
popup.show();
Button saveRecordBtn = (Button) popup
.findViewById(R.id.save_record);
saveRecordBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alert = new AlertDialog.Builder(
Quiz.this);
alert.setTitle("Enter your name");
// Set an EditText view to get user
// input
final EditText input = new EditText(
Quiz.this);
alert.setView(input);
alert.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
String value = input
.getText()
.toString();
// Do something with
// value!
setHighScore(value,
totalScore,
level);
popup.dismiss();
}
});
alert.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
Button quitToMenuBtn = (Button) popup
.findViewById(R.id.quit_to_menu);
quitToMenuBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent backToMenu = new Intent(
Quiz.this, MainMenu.class);
startActivity(backToMenu);
}
});
Button nextLevelBtn = (Button) popup
.findViewById(R.id.next_level);
nextLevelBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
level++;
totalScore += 1000;
lives += 2;
Intent nextLevel = new Intent(
Quiz.this, Game.class);
nextLevel.putExtra("Level", ""
+ level);
nextLevel.putExtra("Total Score",
"" + totalScore);
nextLevel.putExtra("Lives", ""
+ lives);
startActivity(nextLevel);
finish();
}
});
Button postToFbBtn = (Button) popup
.findViewById(R.id.post_to_fb);
postToFbBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
}, 2000);
}
}, 500);
}
/*
* Show map procedure
*
* @author 8A Tran Trong Viet
*/
protected void showMap() {
// remember we will not show 0th and last Row and Columns
// they are used for calculation purposes only
for (int row = 1; row < numberOfRows + 1; row++) {
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new LayoutParams(
(cellWidth + 2 * cellPadding) * numberOfColumns, cellWidth
+ 2 * cellPadding));
for (int column = 1; column < numberOfColumns + 1; column++) {
cells[row][column].setLayoutParams(new LayoutParams(cellWidth
+ 2 * cellPadding, cellWidth + 2 * cellPadding));
cells[row][column].setPadding(cellPadding, cellPadding,
cellPadding, cellPadding);
tableRow.addView(cells[row][column]);
}
map.addView(tableRow, new TableLayout.LayoutParams(
(cellWidth + 2 * cellPadding) * numberOfColumns, cellWidth
+ 2 * cellPadding));
}
}
/*
* Generate the map
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the position of clicked cell
*
* @param columnClicked the position of clicked cell
*/
private void genMap() {
genTraps();
setTheNumberOfSurroundingTrap();
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
if (cells[row][column].getNumberOfTrapsInSurrounding() == 0) {
rippleUncover(row, column);
return;
}
}
}
}
/*
* Generate the traps position in map
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the position of the first-clicked-cell
*
* @param columnClicked the position of the first-clicked-cell
*/
private void genTraps() {
Random rand = new Random();
int trapRow, trapColumn;
// set traps excluding the location where user clicked
for (int row = 0; row < totalTraps; row++) {
trapColumn = rand.nextInt(numberOfColumns);
trapRow = rand.nextInt(numberOfRows);
cells[trapRow + 1][trapColumn + 1].setTrap();
}
}
/*
* Set the number of surrounding trap
*
* @author 8A Tran Trong Viet
*/
private void setTheNumberOfSurroundingTrap() {
int nearByTrapCount;
// count number of traps in surrounding blocks
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
// for each block find nearby trap count
nearByTrapCount = 0;
if ((row != 0) && (row != (numberOfRows + 1)) && (column != 0)
&& (column != (numberOfColumns + 1))) {
// check in all nearby blocks
for (int previousRow = -1; previousRow < 2; previousRow++) {
for (int previousColumn = -1; previousColumn < 2; previousColumn++) {
if (cells[row + previousRow][column
+ previousColumn].hasTrap()) {
// a trap was found so increment the counter
nearByTrapCount++;
}
}
}
cells[row][column]
.setNumberOfTrapsInSurrounding(nearByTrapCount);
}
// for side rows (0th and last row/column)
// set count as 9 and mark it as opened
else {
cells[row][column].setNumberOfTrapsInSurrounding(9);
cells[row][column].OpenCell();
}
}
}
}
/*
* Open the cells which surrounded the no-trap-surrounded cell continuously
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the row of the clicked position
*
* @param columnClicked the column of the clicked position
*/
private void rippleUncover(int rowClicked, int columnClicked) {
if (cells[rowClicked][columnClicked].hasTrap()) {
return;
}
if (!cells[rowClicked][columnClicked].isClickable()) {
return;
}
cells[rowClicked][columnClicked].OpenCell();
if (cells[rowClicked][columnClicked].getNumberOfTrapsInSurrounding() != 0) {
return;
}
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
// check all the above checked conditions
// if met then open subsequent blocks
if (cells[rowClicked + row - 1][columnClicked + column - 1]
.isCovered()
&& (rowClicked + row - 1 > 0)
&& (columnClicked + column - 1 > 0)
&& (rowClicked + row - 1 < numberOfRows + 1)
&& (columnClicked + column - 1 < numberOfColumns + 1)) {
rippleUncover(rowClicked + row - 1, columnClicked + column
- 1);
}
}
}
}
/*
* Set high score
*
* @author 8A Tran Trong Viet
*
* @param sc: savedInstanceState: the state of previous Quiz
*/
public void setHighScore(String playerName, int score, int level) {
try {
if (score > 0) {
SharedPreferences.Editor scoreEdit = QuizPrefs.edit();
// get existing scores
String scores = QuizPrefs.getString("highScores", "");
// check for scores
if (scores.length() > 0) {
List<Score> scoreStrings = new ArrayList<Score>();
String[] exScores = scores.split("\\|");
// add score object for each
for (String eSc : exScores) {
String[] parts = eSc.split(" - ");
scoreStrings
.add(new Score(parts[0], Integer
.parseInt(parts[1]), Integer
.parseInt(parts[2])));
}
// new score
Score newScore = new Score(playerName, score, level);
scoreStrings.add(newScore);
Collections.sort(scoreStrings);
// get top ten
StringBuilder scoreBuild = new StringBuilder("");
for (int s = 0; s < scoreStrings.size(); s++) {
if (s >= 10)
break;
if (s > 0)
scoreBuild.append("|");
scoreBuild.append(scoreStrings.get(s).getScoreText());
}
// write to prefs
scoreEdit.putString("highScores", scoreBuild.toString());
scoreEdit.commit();
} else {
// no existing scores
scoreEdit.putString("highScores", "" + playerName + " - "
+ score + " - " + level);
scoreEdit.commit();
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Start time time
*
* @author 8A Tran Trong Viet
*/
public void startTimer() {
clock.removeCallbacks(updateTimeElasped);
clock.postDelayed(updateTimeElasped, 1000);
}
/*
* Stop the time
*
* @author 8A Tran Trong Viet
*/
public void stopTimer() {
// disable call backs
clock.removeCallbacks(updateTimeElasped);
}
/*
* This properties must be set up for handling the clock
*
* @author 8A Tran Trong Viet
*/
private Runnable updateTimeElasped = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long currentMilliseconds = System.currentTimeMillis();
--timer;
if (!isQuizOver) {
timeText.setText("" + timer);
}
// add notification
clock.postAtTime(this, currentMilliseconds);
// notify to call back after 1 seconds
// basically to remain in the timer loop
clock.postDelayed(updateTimeElasped, 1000);
if (timer == 0) {
finishGame(0, 0);
}
}
};
}
| techcamp15-vietnam/team08 | src/com/example/treasurehunt/Quiz.java | 7,849 | // get top ten | line_comment | nl | package com.example.treasurehunt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
/*
* The quiz level
*
* @author group 8
*/
public class Quiz extends Activity {
/*
* Properties
*/
private TableLayout map;
private Cell cells[][];
private int numberOfRows = 0;
private int numberOfColumns = 0;
private int totalTraps = 0;
private int level = 1;
private int lives = 0;
private int totalScore = 0;
private int step = 0;
private int cellWidth = 34;
private int cellPadding = 2;
// Tracking time
private Handler clock;
private int timer;
private boolean isQuizOver;
private boolean isQuizStart;
// Texts
Typeface font;
TextView levelText, scoreText, timeText, livesText, finalScoreText,
finalTimeText;;
// UI
ImageView mImgViewResult;
// Save Score
private SharedPreferences QuizPrefs;
public static final String Quiz_PREFS = "ArithmeticFile";
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_root);
Options option = new Options();
option.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.gamebg, option);
if (bmp != null) {
layout.setBackgroundDrawable(new BitmapDrawable(getResources(), bmp));
}
map = (TableLayout) findViewById(R.id.Map);
try {
Bundle extras = getIntent().getExtras();
if (extras != null) {
String val1 = extras.getString("Level");
level = Integer.parseInt(val1);
val1 = extras.getString("Total Score");
totalScore = Integer.parseInt(val1);
val1 = extras.getString("Lives");
lives = Integer.parseInt(val1);
} else {
Toast.makeText(this, "Cannot load the game", Toast.LENGTH_SHORT)
.show();
Intent backToMainMenu = new Intent(Quiz.this, MainMenu.class);
startActivity(backToMainMenu);
}
} catch (Exception e) {
Toast.makeText(this, "Cannot load the game", Toast.LENGTH_SHORT)
.show();
Intent backToMainMenu = new Intent(Quiz.this, MainMenu.class);
startActivity(backToMainMenu);
}
initView();
quizControl(level);
startQuizGame();
}
/*
* Initial view
*
* @author 8A Tran Trong Viet
*/
private void initView() {
font = Typeface.createFromAsset(getBaseContext().getAssets(),
"fonts/FRANCHISE-BOLD.TTF");
levelText = (TextView) findViewById(R.id.levelText);
levelText.setTypeface(font);
scoreText = (TextView) findViewById(R.id.scoreText);
scoreText.setTypeface(font);
timeText = (TextView) findViewById(R.id.timeText);
timeText.setTypeface(font);
livesText = (TextView) findViewById(R.id.livesText);
livesText.setTypeface(font);
levelText.setText("Quiz " + level);
scoreText.setText("" + totalScore);
livesText.setText("" + lives);
mImgViewResult = (ImageView) findViewById(R.id.img_result);
numberOfRows = 16;
numberOfColumns = 30;
clock = new Handler();
}
private void quizControl(int _level) {
switch (_level) {
case 5:
setUpQuiz(300, 60);
break;
case 10:
setUpQuiz(300, 90);
break;
default:
break;
}
}
/*
* Set up the Quiz properties
*
* @author 8A Tran Trong Viet
*
* @param playTime the time of current level
*
* @numberOfTraps the number of traps in current level
*
* @score the current score
*
* @_lives the current lives
*/
private void setUpQuiz(int playTime, int numberOfTraps) {
totalTraps = numberOfTraps;
timer = playTime;
}
/*
* Start the Quiz
*
* @author 8A Tran Trong Viet
*/
private void startQuizGame() {
createMap();
showMap();
isQuizOver = false;
isQuizStart = false;
timeText.setText("" + timer);
genMap();
}
/*
* Create new map
*
* @author 8A Tran Trong Viet
*/
protected void createMap() {
// We make more 2 row and column, the 0 row/column and the last one are
// not showed
cells = new Cell[numberOfRows + 2][numberOfColumns + 2];
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
cells[row][column] = new Cell(this);
cells[row][column].setDefaults();
final int currentRow = row;
final int currentColumn = column;
cells[row][column].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
onClickOnCellHandle(currentRow, currentColumn);
}
});
}
}
}
/*
* This method handles the on click event
*
* @author 8A Tran Trong Viet
*
* @param currentRow the position of the clicked cell
*
* @param currentCol the position of the clicked cell
*/
private void onClickOnCellHandle(int currentRow, int currentColumn) {
if (!isQuizStart) {
startTimer();
isQuizStart = true;
}
if (cells[currentRow][currentColumn].isCovered()) {
rippleUncover(currentRow, currentColumn);
if (cells[currentRow][currentColumn].hasTrap()) {
cells[currentRow][currentColumn].OpenCell();
finishGame(currentRow, currentColumn);
} else {
step++;
}
if (checkGameWin(cells[currentRow][currentColumn])) {
winGame();
}
}
}
/*
* Check the game wins or not (should do this for changing rules)
*
* @author 8A Tran Trong Viet
*
* @param cell the cell which is clicked
*/
private boolean checkGameWin(Cell cell) {
return step == 10;
}
/*
* finish the game
*
* @author 8A Tran Trong Viet
*/
private void finishGame(int currentRow, int currentColumn) {
stopTimer(); // stop timer
isQuizStart = false;
// show all traps
// disable all traps
for (int row = 1; row < numberOfRows + 1; row++) {
for (int column = 1; column < numberOfColumns + 1; column++) {
// disable block
// cells[row][column].setCellAsDisabled(false);
cells[row][column].disableCell();
}
}
// trigger trap
cells[currentRow][currentColumn].triggerTrap();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setBackgroundResource(R.drawable.trapped);
mImgViewResult.setVisibility(View.VISIBLE);
mImgViewResult.bringToFront();
mImgViewResult.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setVisibility(View.GONE);
if (!isQuizOver) {
isQuizOver = true; // mark game as over
final Dialog popup = new Dialog(Quiz.this);
popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
popup.getWindow()
.setBackgroundDrawable(
new ColorDrawable(
android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.win_popup);
popup.setCancelable(false);
finalScoreText = (TextView) popup
.findViewById(R.id.finalScore);
finalScoreText.setTypeface(font);
finalScoreText.setText("" + totalScore);
finalTimeText = (TextView) popup
.findViewById(R.id.finalTime);
finalTimeText.setTypeface(font);
finalTimeText.setText("" + timer);
popup.show();
Button saveRecordBtn = (Button) popup
.findViewById(R.id.save_record);
saveRecordBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alert = new AlertDialog.Builder(
Quiz.this);
alert.setTitle("Enter your name");
// Set an EditText view to get user
// input
final EditText input = new EditText(
Quiz.this);
alert.setView(input);
alert.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
String value = input
.getText()
.toString();
// Do something with
// value!
setHighScore(value,
totalScore,
level);
popup.dismiss();
}
});
alert.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
Button quitToMenuBtn = (Button) popup
.findViewById(R.id.quit_to_menu);
quitToMenuBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent backToMenu = new Intent(
Quiz.this, MainMenu.class);
startActivity(backToMenu);
}
});
Button nextLevelBtn = (Button) popup
.findViewById(R.id.next_level);
nextLevelBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
level++;
Intent nextLevel = new Intent(
Quiz.this, Game.class);
nextLevel.putExtra("Level", ""
+ level);
nextLevel.putExtra("Total Score",
"" + totalScore);
nextLevel.putExtra("Lives", ""
+ lives);
startActivity(nextLevel);
finish();
}
});
Button postToFbBtn = (Button) popup
.findViewById(R.id.post_to_fb);
postToFbBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
}, 2000);
}
}, 500);
}
/*
* Win the game
*
* @author 8A Tran Trong Viet
*/
private void winGame() {
// reset all stuffs
stopTimer();
isQuizStart = false;
totalScore += 500;
// disable all buttons
// set flagged all un-flagged blocks
for (int row = 1; row < numberOfRows + 1; row++) {
for (int column = 1; column < numberOfColumns + 1; column++) {
cells[row][column].setClickable(false);
if (cells[row][column].hasTrap()) {
cells[row][column].setTrapIcon(true);
}
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setBackgroundResource(R.drawable.congrat);
mImgViewResult.setVisibility(View.VISIBLE);
mImgViewResult.bringToFront();
mImgViewResult.postDelayed(new Runnable() {
@Override
public void run() {
mImgViewResult.setVisibility(View.GONE);
if (!isQuizOver) {
isQuizOver = true; // mark game as over
final Dialog popup = new Dialog(Quiz.this);
popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
popup.getWindow()
.setBackgroundDrawable(
new ColorDrawable(
android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.win_popup);
popup.setCancelable(false);
finalScoreText = (TextView) popup
.findViewById(R.id.finalScore);
finalScoreText.setTypeface(font);
finalScoreText.setText("" + totalScore);
finalTimeText = (TextView) popup
.findViewById(R.id.finalTime);
finalTimeText.setTypeface(font);
finalTimeText.setText("" + timer);
popup.show();
Button saveRecordBtn = (Button) popup
.findViewById(R.id.save_record);
saveRecordBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alert = new AlertDialog.Builder(
Quiz.this);
alert.setTitle("Enter your name");
// Set an EditText view to get user
// input
final EditText input = new EditText(
Quiz.this);
alert.setView(input);
alert.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
String value = input
.getText()
.toString();
// Do something with
// value!
setHighScore(value,
totalScore,
level);
popup.dismiss();
}
});
alert.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
Button quitToMenuBtn = (Button) popup
.findViewById(R.id.quit_to_menu);
quitToMenuBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent backToMenu = new Intent(
Quiz.this, MainMenu.class);
startActivity(backToMenu);
}
});
Button nextLevelBtn = (Button) popup
.findViewById(R.id.next_level);
nextLevelBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
level++;
totalScore += 1000;
lives += 2;
Intent nextLevel = new Intent(
Quiz.this, Game.class);
nextLevel.putExtra("Level", ""
+ level);
nextLevel.putExtra("Total Score",
"" + totalScore);
nextLevel.putExtra("Lives", ""
+ lives);
startActivity(nextLevel);
finish();
}
});
Button postToFbBtn = (Button) popup
.findViewById(R.id.post_to_fb);
postToFbBtn
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
}, 2000);
}
}, 500);
}
/*
* Show map procedure
*
* @author 8A Tran Trong Viet
*/
protected void showMap() {
// remember we will not show 0th and last Row and Columns
// they are used for calculation purposes only
for (int row = 1; row < numberOfRows + 1; row++) {
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new LayoutParams(
(cellWidth + 2 * cellPadding) * numberOfColumns, cellWidth
+ 2 * cellPadding));
for (int column = 1; column < numberOfColumns + 1; column++) {
cells[row][column].setLayoutParams(new LayoutParams(cellWidth
+ 2 * cellPadding, cellWidth + 2 * cellPadding));
cells[row][column].setPadding(cellPadding, cellPadding,
cellPadding, cellPadding);
tableRow.addView(cells[row][column]);
}
map.addView(tableRow, new TableLayout.LayoutParams(
(cellWidth + 2 * cellPadding) * numberOfColumns, cellWidth
+ 2 * cellPadding));
}
}
/*
* Generate the map
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the position of clicked cell
*
* @param columnClicked the position of clicked cell
*/
private void genMap() {
genTraps();
setTheNumberOfSurroundingTrap();
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
if (cells[row][column].getNumberOfTrapsInSurrounding() == 0) {
rippleUncover(row, column);
return;
}
}
}
}
/*
* Generate the traps position in map
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the position of the first-clicked-cell
*
* @param columnClicked the position of the first-clicked-cell
*/
private void genTraps() {
Random rand = new Random();
int trapRow, trapColumn;
// set traps excluding the location where user clicked
for (int row = 0; row < totalTraps; row++) {
trapColumn = rand.nextInt(numberOfColumns);
trapRow = rand.nextInt(numberOfRows);
cells[trapRow + 1][trapColumn + 1].setTrap();
}
}
/*
* Set the number of surrounding trap
*
* @author 8A Tran Trong Viet
*/
private void setTheNumberOfSurroundingTrap() {
int nearByTrapCount;
// count number of traps in surrounding blocks
for (int row = 0; row < numberOfRows + 2; row++) {
for (int column = 0; column < numberOfColumns + 2; column++) {
// for each block find nearby trap count
nearByTrapCount = 0;
if ((row != 0) && (row != (numberOfRows + 1)) && (column != 0)
&& (column != (numberOfColumns + 1))) {
// check in all nearby blocks
for (int previousRow = -1; previousRow < 2; previousRow++) {
for (int previousColumn = -1; previousColumn < 2; previousColumn++) {
if (cells[row + previousRow][column
+ previousColumn].hasTrap()) {
// a trap was found so increment the counter
nearByTrapCount++;
}
}
}
cells[row][column]
.setNumberOfTrapsInSurrounding(nearByTrapCount);
}
// for side rows (0th and last row/column)
// set count as 9 and mark it as opened
else {
cells[row][column].setNumberOfTrapsInSurrounding(9);
cells[row][column].OpenCell();
}
}
}
}
/*
* Open the cells which surrounded the no-trap-surrounded cell continuously
*
* @author 8A Tran Trong Viet
*
* @param rowClicked the row of the clicked position
*
* @param columnClicked the column of the clicked position
*/
private void rippleUncover(int rowClicked, int columnClicked) {
if (cells[rowClicked][columnClicked].hasTrap()) {
return;
}
if (!cells[rowClicked][columnClicked].isClickable()) {
return;
}
cells[rowClicked][columnClicked].OpenCell();
if (cells[rowClicked][columnClicked].getNumberOfTrapsInSurrounding() != 0) {
return;
}
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
// check all the above checked conditions
// if met then open subsequent blocks
if (cells[rowClicked + row - 1][columnClicked + column - 1]
.isCovered()
&& (rowClicked + row - 1 > 0)
&& (columnClicked + column - 1 > 0)
&& (rowClicked + row - 1 < numberOfRows + 1)
&& (columnClicked + column - 1 < numberOfColumns + 1)) {
rippleUncover(rowClicked + row - 1, columnClicked + column
- 1);
}
}
}
}
/*
* Set high score
*
* @author 8A Tran Trong Viet
*
* @param sc: savedInstanceState: the state of previous Quiz
*/
public void setHighScore(String playerName, int score, int level) {
try {
if (score > 0) {
SharedPreferences.Editor scoreEdit = QuizPrefs.edit();
// get existing scores
String scores = QuizPrefs.getString("highScores", "");
// check for scores
if (scores.length() > 0) {
List<Score> scoreStrings = new ArrayList<Score>();
String[] exScores = scores.split("\\|");
// add score object for each
for (String eSc : exScores) {
String[] parts = eSc.split(" - ");
scoreStrings
.add(new Score(parts[0], Integer
.parseInt(parts[1]), Integer
.parseInt(parts[2])));
}
// new score
Score newScore = new Score(playerName, score, level);
scoreStrings.add(newScore);
Collections.sort(scoreStrings);
// get top<SUF>
StringBuilder scoreBuild = new StringBuilder("");
for (int s = 0; s < scoreStrings.size(); s++) {
if (s >= 10)
break;
if (s > 0)
scoreBuild.append("|");
scoreBuild.append(scoreStrings.get(s).getScoreText());
}
// write to prefs
scoreEdit.putString("highScores", scoreBuild.toString());
scoreEdit.commit();
} else {
// no existing scores
scoreEdit.putString("highScores", "" + playerName + " - "
+ score + " - " + level);
scoreEdit.commit();
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Start time time
*
* @author 8A Tran Trong Viet
*/
public void startTimer() {
clock.removeCallbacks(updateTimeElasped);
clock.postDelayed(updateTimeElasped, 1000);
}
/*
* Stop the time
*
* @author 8A Tran Trong Viet
*/
public void stopTimer() {
// disable call backs
clock.removeCallbacks(updateTimeElasped);
}
/*
* This properties must be set up for handling the clock
*
* @author 8A Tran Trong Viet
*/
private Runnable updateTimeElasped = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long currentMilliseconds = System.currentTimeMillis();
--timer;
if (!isQuizOver) {
timeText.setText("" + timer);
}
// add notification
clock.postAtTime(this, currentMilliseconds);
// notify to call back after 1 seconds
// basically to remain in the timer loop
clock.postDelayed(updateTimeElasped, 1000);
if (timer == 0) {
finishGame(0, 0);
}
}
};
}
|
28039_0 | public class VariablesOperatorsOpdracht7 {
//Wat is een voordeel van Strict Typing? Het werkt als een labeltool en kan regels beter herkennen.
//Wat is een voordeel van Weak Typing? Minder typen en minder denken maar meer testen.
}
| techgrounds/agile-tester-apriljml | Agile-Java/BasicsJava/src/VariablesOperatorsOpdracht7.java | 72 | //Wat is een voordeel van Strict Typing? Het werkt als een labeltool en kan regels beter herkennen. | line_comment | nl | public class VariablesOperatorsOpdracht7 {
//Wat is<SUF>
//Wat is een voordeel van Weak Typing? Minder typen en minder denken maar meer testen.
}
|
162710_0 | package jo4neo.impl;
import static jo4neo.Relationships.JO4NEO_HAS_TYPE;
import static jo4neo.impl.TypeWrapperFactory.$;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import jo4neo.Nodeid;
import jo4neo.util.RelationFactory;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.KernelEventHandler;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.index.lucene.LuceneTimeline;
import org.neo4j.index.lucene.TimelineIndex;
class IndexedNeo implements GraphDatabaseService {
private GraphDatabaseService neo;
private Index<Node> index;
private Index<Node> ftindex;
private RelationFactory relFactory;
private boolean isClosed = false;
private Map<Class<?>, TimelineIndex<Node>> timelines;
private Map<Class<?>, Index<Node>> uniques;
public IndexedNeo(GraphDatabaseService neo) {
this.neo = neo;
IndexManager im = neo.index();
index = im.forNodes("default");
ftindex = im.forNodes("default-fulltext", MapUtil.stringMap(
IndexManager.PROVIDER, "lucene", "type", "fulltext"));
;
relFactory = new RelationFactoryImpl();
timelines = new HashMap<Class<?>, TimelineIndex<Node>>();
}
public synchronized void close() {
isClosed = true;
}
public Index<Node> getIndexService() {
return index;
}
public Index<Node> getFullTextIndexService() {
return ftindex;
}
public Transaction beginTx() {
return neo.beginTx();
}
public Iterable<Node> getAllNodes() {
return neo.getAllNodes();
}
public Node getNodeById(long arg0) {
return neo.getNodeById(arg0);
}
public Node getNodeById(Nodeid id) {
return neo.getNodeById(id.id());
}
public Node getReferenceNode() {
return neo.getReferenceNode();
}
public Relationship getRelationshipById(long arg0) {
return neo.getRelationshipById(arg0);
}
public Iterable<RelationshipType> getRelationshipTypes() {
return neo.getRelationshipTypes();
}
public void shutdown() {
close();
neo.shutdown();
}
public RelationFactory getRelationFactory() {
return relFactory;
}
public Node createNode() {
return neo.createNode();
}
public Node asNode(Object o) {
return getNodeById($(o).id(o));
}
public Node getMetaNode(Class<?> type) {
Node metanode;
RelationshipType relType = DynamicRelationshipType.withName(type
.getName());
Node root = neo.getReferenceNode();
Iterable<Relationship> r = root.getRelationships(relType);
if (r.iterator().hasNext())
metanode = r.iterator().next().getEndNode();
else {
Transaction tx = neo.beginTx();
try {
metanode = neo.createNode();
metanode.setProperty(Nodeid.class.getName(), type.getName());
root.createRelationshipTo(metanode, relType);
tx.success();
} finally {
tx.finish();
}
}
return metanode;
}
public TimelineIndex<Node> getTimeLine(Class<?> c) {
if (timelines.containsKey(c))
return timelines.get(c);
// TODO
// Node metaNode = getMetaNode(c);
TimelineIndex<Node> t = new LuceneTimeline<Node>(neo, neo.index()
.forNodes(c.getName()));
timelines.put(c, t);
return t;
}
public boolean isClosed() {
return isClosed;
}
public IndexManager index() {
return neo.index();
}
public KernelEventHandler registerKernelEventHandler(
KernelEventHandler handler) {
return neo.registerKernelEventHandler(handler);
}
public <T> TransactionEventHandler<T> registerTransactionEventHandler(
TransactionEventHandler<T> handler) {
return neo.registerTransactionEventHandler(handler);
}
public KernelEventHandler unregisterKernelEventHandler(
KernelEventHandler handler) {
return neo.unregisterKernelEventHandler(handler);
}
public <T> TransactionEventHandler<T> unregisterTransactionEventHandler(
TransactionEventHandler<T> handler) {
return neo.unregisterTransactionEventHandler(handler);
}
public Node getURINode(URI uri) {
Transaction t = neo.beginTx();
try {
Node n = getIndexService().get(URI.class.getName(), uri.toString()).getSingle();
if (n == null) {
n = createNode();
getIndexService().add(n, URI.class.getName(), uri.toString());
n.setProperty("uri", uri.toString());
n.setProperty(Nodeid.class.getName(), URI.class.getName());
// find metanode for type t
Node metanode = getMetaNode(URI.class);
n.createRelationshipTo(metanode, JO4NEO_HAS_TYPE);
}
t.success();
return n;
} finally {
t.finish();
}
}
}
/**
* jo4neo is a java object binding library for neo4j Copyright (C) 2009 Taylor
* Cowan
*
* 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 the License, 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 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/>.
*/
| teknologist/neoorm | neoorm/src/main/java/jo4neo/impl/IndexedNeo.java | 1,915 | // Node metaNode = getMetaNode(c);
| line_comment | nl | package jo4neo.impl;
import static jo4neo.Relationships.JO4NEO_HAS_TYPE;
import static jo4neo.impl.TypeWrapperFactory.$;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import jo4neo.Nodeid;
import jo4neo.util.RelationFactory;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.KernelEventHandler;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.index.lucene.LuceneTimeline;
import org.neo4j.index.lucene.TimelineIndex;
class IndexedNeo implements GraphDatabaseService {
private GraphDatabaseService neo;
private Index<Node> index;
private Index<Node> ftindex;
private RelationFactory relFactory;
private boolean isClosed = false;
private Map<Class<?>, TimelineIndex<Node>> timelines;
private Map<Class<?>, Index<Node>> uniques;
public IndexedNeo(GraphDatabaseService neo) {
this.neo = neo;
IndexManager im = neo.index();
index = im.forNodes("default");
ftindex = im.forNodes("default-fulltext", MapUtil.stringMap(
IndexManager.PROVIDER, "lucene", "type", "fulltext"));
;
relFactory = new RelationFactoryImpl();
timelines = new HashMap<Class<?>, TimelineIndex<Node>>();
}
public synchronized void close() {
isClosed = true;
}
public Index<Node> getIndexService() {
return index;
}
public Index<Node> getFullTextIndexService() {
return ftindex;
}
public Transaction beginTx() {
return neo.beginTx();
}
public Iterable<Node> getAllNodes() {
return neo.getAllNodes();
}
public Node getNodeById(long arg0) {
return neo.getNodeById(arg0);
}
public Node getNodeById(Nodeid id) {
return neo.getNodeById(id.id());
}
public Node getReferenceNode() {
return neo.getReferenceNode();
}
public Relationship getRelationshipById(long arg0) {
return neo.getRelationshipById(arg0);
}
public Iterable<RelationshipType> getRelationshipTypes() {
return neo.getRelationshipTypes();
}
public void shutdown() {
close();
neo.shutdown();
}
public RelationFactory getRelationFactory() {
return relFactory;
}
public Node createNode() {
return neo.createNode();
}
public Node asNode(Object o) {
return getNodeById($(o).id(o));
}
public Node getMetaNode(Class<?> type) {
Node metanode;
RelationshipType relType = DynamicRelationshipType.withName(type
.getName());
Node root = neo.getReferenceNode();
Iterable<Relationship> r = root.getRelationships(relType);
if (r.iterator().hasNext())
metanode = r.iterator().next().getEndNode();
else {
Transaction tx = neo.beginTx();
try {
metanode = neo.createNode();
metanode.setProperty(Nodeid.class.getName(), type.getName());
root.createRelationshipTo(metanode, relType);
tx.success();
} finally {
tx.finish();
}
}
return metanode;
}
public TimelineIndex<Node> getTimeLine(Class<?> c) {
if (timelines.containsKey(c))
return timelines.get(c);
// TODO
// Node metaNode<SUF>
TimelineIndex<Node> t = new LuceneTimeline<Node>(neo, neo.index()
.forNodes(c.getName()));
timelines.put(c, t);
return t;
}
public boolean isClosed() {
return isClosed;
}
public IndexManager index() {
return neo.index();
}
public KernelEventHandler registerKernelEventHandler(
KernelEventHandler handler) {
return neo.registerKernelEventHandler(handler);
}
public <T> TransactionEventHandler<T> registerTransactionEventHandler(
TransactionEventHandler<T> handler) {
return neo.registerTransactionEventHandler(handler);
}
public KernelEventHandler unregisterKernelEventHandler(
KernelEventHandler handler) {
return neo.unregisterKernelEventHandler(handler);
}
public <T> TransactionEventHandler<T> unregisterTransactionEventHandler(
TransactionEventHandler<T> handler) {
return neo.unregisterTransactionEventHandler(handler);
}
public Node getURINode(URI uri) {
Transaction t = neo.beginTx();
try {
Node n = getIndexService().get(URI.class.getName(), uri.toString()).getSingle();
if (n == null) {
n = createNode();
getIndexService().add(n, URI.class.getName(), uri.toString());
n.setProperty("uri", uri.toString());
n.setProperty(Nodeid.class.getName(), URI.class.getName());
// find metanode for type t
Node metanode = getMetaNode(URI.class);
n.createRelationshipTo(metanode, JO4NEO_HAS_TYPE);
}
t.success();
return n;
} finally {
t.finish();
}
}
}
/**
* jo4neo is a java object binding library for neo4j Copyright (C) 2009 Taylor
* Cowan
*
* 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 the License, 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 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/>.
*/
|
186609_1 | package com.tencent.liteav.demo;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDexApplication;
import android.util.Log;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.qcloud.ugckit.UGCKit;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.ugc.TXUGCBase;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//import com.squareup.leakcanary.LeakCanary;
//import com.squareup.leakcanary.RefWatcher;
public class DemoApplication extends MultiDexApplication {
private static String TAG = "DemoApplication";
//配置bugly组件的appId
private static final String BUGLY_APPID = "";
// 配置bugly组件的APP渠道号
private static final String BUGLY_APP_CHANNEL = "";
//配置bugly组件的调试模式(true或者false)
private static final boolean BUGLY_ENABLE_DEBUG = true;
// private RefWatcher mRefWatcher;
private static DemoApplication instance;
// 如何获取License? 请参考官网指引 https://cloud.tencent.com/document/product/454/34750
String licenceUrl = "请替换成您的licenseUrl";
String licenseKey = "请替换成您的licenseKey";
@Override
public void onCreate() {
super.onCreate();
instance = this;
TXLiveBase.setConsoleEnabled(true);
initBugly();
UGCKit.init(this);
TXLiveBase.getInstance().setLicence(instance, licenceUrl, licenseKey);
// 短视频licence设置
TXUGCBase.getInstance().setLicence(this, licenceUrl, licenseKey);
UGCKit.init(this);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
builder.detectFileUriExposure();
}
closeAndroidPDialog();
CallService.start(this);
}
// public static RefWatcher getRefWatcher(Context context) {
// DemoApplication application = (DemoApplication) context.getApplicationContext();
// return application.mRefWatcher;
// }
public static DemoApplication getApplication() {
return instance;
}
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
//配置bugly组件的APP ID,bugly组件为腾讯提供的用于crash上报,分析和升级的开放组件,如果您不需要该组件,可以自行移除
private void initBugly() {
CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
strategy.setAppVersion(TXLiveBase.getSDKVersionStr());
strategy.setAppChannel(BUGLY_APP_CHANNEL);
//监听安装包下载状态
Beta.downloadListener = new DownloadListener() {
@Override
public void onReceive(DownloadTask downloadTask) {
}
@Override
public void onCompleted(DownloadTask downloadTask) {
Log.d(TAG,"downloadListener download apk file success");
}
@Override
public void onFailed(DownloadTask downloadTask, int i, String s) {
Log.d(TAG,"downloadListener download apk file fail");
}
};
//监听APP升级状态
Beta.upgradeStateListener = new UpgradeStateListener(){
@Override
public void onUpgradeFailed(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade failed");
}
@Override
public void onUpgradeSuccess(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade success");
}
@Override
public void onUpgradeNoVersion(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade has no new version");
}
@Override
public void onUpgrading(boolean b) {
Log.d(TAG,"upgradeStateListener upgrading");
}
@Override
public void onDownloadCompleted(boolean b) {
Log.d(TAG,"upgradeStateListener download apk file success");
}
};
Bugly.init(getApplicationContext(), BUGLY_APPID, BUGLY_ENABLE_DEBUG, strategy);
}
} | tencentyun/LiteAVProfessional_Android | Demo/app/src/main/java/com/tencent/liteav/demo/DemoApplication.java | 1,504 | // 如何获取License? 请参考官网指引 https://cloud.tencent.com/document/product/454/34750 | line_comment | nl | package com.tencent.liteav.demo;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDexApplication;
import android.util.Log;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.qcloud.ugckit.UGCKit;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.ugc.TXUGCBase;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//import com.squareup.leakcanary.LeakCanary;
//import com.squareup.leakcanary.RefWatcher;
public class DemoApplication extends MultiDexApplication {
private static String TAG = "DemoApplication";
//配置bugly组件的appId
private static final String BUGLY_APPID = "";
// 配置bugly组件的APP渠道号
private static final String BUGLY_APP_CHANNEL = "";
//配置bugly组件的调试模式(true或者false)
private static final boolean BUGLY_ENABLE_DEBUG = true;
// private RefWatcher mRefWatcher;
private static DemoApplication instance;
// 如何获取License? 请参考官网指引<SUF>
String licenceUrl = "请替换成您的licenseUrl";
String licenseKey = "请替换成您的licenseKey";
@Override
public void onCreate() {
super.onCreate();
instance = this;
TXLiveBase.setConsoleEnabled(true);
initBugly();
UGCKit.init(this);
TXLiveBase.getInstance().setLicence(instance, licenceUrl, licenseKey);
// 短视频licence设置
TXUGCBase.getInstance().setLicence(this, licenceUrl, licenseKey);
UGCKit.init(this);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
builder.detectFileUriExposure();
}
closeAndroidPDialog();
CallService.start(this);
}
// public static RefWatcher getRefWatcher(Context context) {
// DemoApplication application = (DemoApplication) context.getApplicationContext();
// return application.mRefWatcher;
// }
public static DemoApplication getApplication() {
return instance;
}
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
//配置bugly组件的APP ID,bugly组件为腾讯提供的用于crash上报,分析和升级的开放组件,如果您不需要该组件,可以自行移除
private void initBugly() {
CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
strategy.setAppVersion(TXLiveBase.getSDKVersionStr());
strategy.setAppChannel(BUGLY_APP_CHANNEL);
//监听安装包下载状态
Beta.downloadListener = new DownloadListener() {
@Override
public void onReceive(DownloadTask downloadTask) {
}
@Override
public void onCompleted(DownloadTask downloadTask) {
Log.d(TAG,"downloadListener download apk file success");
}
@Override
public void onFailed(DownloadTask downloadTask, int i, String s) {
Log.d(TAG,"downloadListener download apk file fail");
}
};
//监听APP升级状态
Beta.upgradeStateListener = new UpgradeStateListener(){
@Override
public void onUpgradeFailed(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade failed");
}
@Override
public void onUpgradeSuccess(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade success");
}
@Override
public void onUpgradeNoVersion(boolean b) {
Log.d(TAG,"upgradeStateListener upgrade has no new version");
}
@Override
public void onUpgrading(boolean b) {
Log.d(TAG,"upgradeStateListener upgrading");
}
@Override
public void onDownloadCompleted(boolean b) {
Log.d(TAG,"upgradeStateListener download apk file success");
}
};
Bugly.init(getApplicationContext(), BUGLY_APPID, BUGLY_ENABLE_DEBUG, strategy);
}
} |
404_9 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.lite;
/** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */
public enum DataType {
/** 32-bit single precision floating point. */
FLOAT32(1),
/** 32-bit signed integer. */
INT32(2),
/** 8-bit unsigned integer. */
UINT8(3),
/** 64-bit signed integer. */
INT64(4),
/** Strings. */
STRING(5),
/** Bool. */
BOOL(6),
/** 16-bit signed integer. */
INT16(7),
/** 8-bit signed integer. */
INT8(9);
private final int value;
DataType(int value) {
this.value = value;
}
/** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */
public int byteSize() {
switch (this) {
case FLOAT32:
case INT32:
return 4;
case INT16:
return 2;
case INT8:
case UINT8:
return 1;
case INT64:
return 8;
case BOOL:
// Boolean size is JVM-dependent.
return -1;
case STRING:
return -1;
}
throw new IllegalArgumentException(
"DataType error: DataType " + this + " is not supported yet");
}
/** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */
int c() {
return value;
}
}
| tensorflow/tensorflow | tensorflow/lite/java/src/main/java/org/tensorflow/lite/DataType.java | 577 | // Boolean size is JVM-dependent. | line_comment | nl | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.lite;
/** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */
public enum DataType {
/** 32-bit single precision floating point. */
FLOAT32(1),
/** 32-bit signed integer. */
INT32(2),
/** 8-bit unsigned integer. */
UINT8(3),
/** 64-bit signed integer. */
INT64(4),
/** Strings. */
STRING(5),
/** Bool. */
BOOL(6),
/** 16-bit signed integer. */
INT16(7),
/** 8-bit signed integer. */
INT8(9);
private final int value;
DataType(int value) {
this.value = value;
}
/** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */
public int byteSize() {
switch (this) {
case FLOAT32:
case INT32:
return 4;
case INT16:
return 2;
case INT8:
case UINT8:
return 1;
case INT64:
return 8;
case BOOL:
// Boolean size<SUF>
return -1;
case STRING:
return -1;
}
throw new IllegalArgumentException(
"DataType error: DataType " + this + " is not supported yet");
}
/** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */
int c() {
return value;
}
}
|
197690_0 | package logic;
import constants.SystemCache;
import javafx.geometry.Point2D;
import object.weapon.gun.Gun;
import object.weapon.gun.Pistol;
public class Accessories {
private int cash;
public Gun gunA;
public Gun gunB;
// private int numberOfFragenade;
private Gun currentGun;
public Accessories() {
gunA = new Pistol();
gunB = null;
currentGun = gunA;
}
public void gainCash(int gain) {
this.cash += gain;
SystemCache.getInstance().gameUI.setCash(cash);
}
public boolean costCash(int cost) {
if(this.cash >= cost) {
gainCash(-cost);
return true;
}
return false;
}
public Gun getCurrentGun() {
return this.currentGun;
}
public void swapGun() {
if(gunB == null) return;
currentGun = currentGun == gunA ? gunB : gunA;
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void updateCurrentGun(Point2D aimOrigin, Point2D aimDirection) {
this.currentGun.gunFireListener(aimOrigin, aimDirection);
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void reloadCurrentGun() {
this.currentGun.reload();
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void changeGunA(Gun gun) {
if(this.currentGun == this.gunA) this.currentGun = gun;
this.gunA = gun;
}
public void changeGunB(Gun gun) {
if(this.currentGun == this.gunB) this.currentGun = gun;
this.gunB = gun;
}
}
| tepzilon/progmeth-project | src/logic/Accessories.java | 522 | // private int numberOfFragenade; | line_comment | nl | package logic;
import constants.SystemCache;
import javafx.geometry.Point2D;
import object.weapon.gun.Gun;
import object.weapon.gun.Pistol;
public class Accessories {
private int cash;
public Gun gunA;
public Gun gunB;
// private int<SUF>
private Gun currentGun;
public Accessories() {
gunA = new Pistol();
gunB = null;
currentGun = gunA;
}
public void gainCash(int gain) {
this.cash += gain;
SystemCache.getInstance().gameUI.setCash(cash);
}
public boolean costCash(int cost) {
if(this.cash >= cost) {
gainCash(-cost);
return true;
}
return false;
}
public Gun getCurrentGun() {
return this.currentGun;
}
public void swapGun() {
if(gunB == null) return;
currentGun = currentGun == gunA ? gunB : gunA;
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void updateCurrentGun(Point2D aimOrigin, Point2D aimDirection) {
this.currentGun.gunFireListener(aimOrigin, aimDirection);
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void reloadCurrentGun() {
this.currentGun.reload();
SystemCache.getInstance().accessoriesUI.updateInfo(this);
}
public void changeGunA(Gun gun) {
if(this.currentGun == this.gunA) this.currentGun = gun;
this.gunA = gun;
}
public void changeGunB(Gun gun) {
if(this.currentGun == this.gunB) this.currentGun = gun;
this.gunB = gun;
}
}
|
112660_7 | package org.terifan.truecrypt;
import org.terifan.pagestore.PageStore;
import org.terifan.util.ByteArray;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.zip.CRC32;
public class TrueCryptPageStore implements PageStore, AutoCloseable
{
private final static int VERSION_NUM = 0x063a;
private final static int ENCRYPTION_DATA_UNIT_SIZE = 512;
private final static int PKCS5_SALT_SIZE = 64;
private final static int MASTER_KEYDATA_SIZE = 256;
private final static int VOLUME_HEADER_VERSION = 0x0004;
private final static int TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION = 0x0600;
private final static int TC_VOLUME_HEADER_EFFECTIVE_SIZE = 512;
private final static int TC_HEADER_OFFSET_MAGIC = 64;
private final static int TC_HEADER_OFFSET_VERSION = 68;
private final static int TC_HEADER_OFFSET_REQUIRED_VERSION = 70;
private final static int TC_HEADER_OFFSET_KEY_AREA_CRC = 72;
private final static int TC_HEADER_OFFSET_VOLUME_CREATION_TIME = 76;
private final static int TC_HEADER_OFFSET_MODIFICATION_TIME = 84;
private final static int TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE = 92;
private final static int TC_HEADER_OFFSET_VOLUME_SIZE = 100;
private final static int TC_HEADER_OFFSET_ENCRYPTED_AREA_START = 108;
private final static int TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH = 116;
private final static int TC_HEADER_OFFSET_FLAGS = 124;
private final static int TC_HEADER_OFFSET_HEADER_CRC = 252;
private final static int HEADER_SALT_OFFSET = 0;
private final static int HEADER_ENCRYPTED_DATA_OFFSET = PKCS5_SALT_SIZE;
private final static int HEADER_MASTER_KEYDATA_OFFSET = 256;
private final static int HEADER_ENCRYPTED_DATA_SIZE = (TC_VOLUME_HEADER_EFFECTIVE_SIZE - HEADER_ENCRYPTED_DATA_OFFSET);
public static enum CipherOption
{
AES("aes"),
SERPENT("serpent"),
TWOFISH("twofish"),
TWOFISH_AES("twofish", "aes"),
SERPENT_TWOFISH_AES("serpent", "twofish", "aes"),
AES_SERPENT("aes", "serpent"),
AES_TWOFISH_SERPENT("aes", "twofish", "serpent"),
SERPENT_TWOFISH("serpent", "twofish");
private final String[] mAlgorithms;
CipherOption(String... aAlgorithms)
{
mAlgorithms = aAlgorithms;
}
}
public static enum DigestOption
{
SHA512(1000),
RIPEMD160(2000),
WHIRLPOOL(1000);
private final int mIterations;
private DigestOption(int aIterations)
{
mIterations = aIterations;
}
MessageDigest getDigestInstance()
{
switch (this)
{
case SHA512:
return new SHA512();
case RIPEMD160:
return new RIPEMD160();
case WHIRLPOOL:
return new Whirlpool();
}
throw new RuntimeException();
}
}
private PageStore mPageStore;
private long mVolumeDataAreaOffset;
private long mVolumeDataAreaLength;
private Cipher[] mCiphers;
private Cipher[] mTweakCiphers;
private TrueCryptPageStore(PageStore aPageStore) throws IOException
{
if (aPageStore.getPageSize() != ENCRYPTION_DATA_UNIT_SIZE)
{
throw new IllegalArgumentException("Provided page store must have a " + ENCRYPTION_DATA_UNIT_SIZE + "-byte page size.");
}
mPageStore = aPageStore;
}
public static TrueCryptPageStore open(PageStore aPageStore, String aPassword) throws IOException
{
TrueCryptPageStore tc = new TrueCryptPageStore(aPageStore);
tc.readVolumeHeader(aPassword);
return tc;
}
public static TrueCryptPageStore create(PageStore aPageStore, long aPageCount, String aPassword, CipherOption aCipherOption, DigestOption aDigestOption, Consumer<Long> aProgressCallback) throws IOException
{
aPageStore.resize(aPageCount);
TrueCryptPageStore tc = new TrueCryptPageStore(aPageStore);
tc.format(aProgressCallback);
tc.writeVolumeHeader(aPassword);
return tc;
}
private void readVolumeHeader(String aPassword) throws IOException
{
byte[] headerBuffer = new byte[ENCRYPTION_DATA_UNIT_SIZE];
mPageStore.read(0, headerBuffer);
ArrayList<Callable<Boolean>> tasks = new ArrayList<>();
for (CipherOption cipher : CipherOption.values())
{
for (DigestOption digest : DigestOption.values())
{
VolumeHeaderDecoder task = new VolumeHeaderDecoder(headerBuffer.clone(), cipher, digest, aPassword.getBytes());
tasks.add(task);
}
}
int cpu = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(cpu);
try
{
pool.invokeAll(tasks);
}
catch (InterruptedException e)
{
}
pool.shutdown();
if (mCiphers == null)
{
throw new InvalidKeyException("Incorrect password or an unsupported file version.");
}
}
private void writeVolumeHeader(String aPassword)
{
}
private void setup(byte[] aHeader, String[] aCipherAlgorithms)
{
//Debug.hexDump(aHeader);
// Header version
int headerVersion = ByteArray.BE.getShort(aHeader, TC_HEADER_OFFSET_VERSION);
if (headerVersion > VOLUME_HEADER_VERSION)
{
//throw new RuntimeException("ERR_NEW_VERSION_REQUIRED " + headerVersion);
}
// Check CRC of the header fields
if (headerVersion >= 4)
{
CRC32 crc = new CRC32();
crc.update(aHeader, TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
if (ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_HEADER_CRC) != (int)crc.getValue())
{
throw new RuntimeException("Bad header CRC");
}
}
else
{
throw new RuntimeException("Bad version: " + headerVersion);
}
// Required program version
int requiredProgramVersion = ByteArray.BE.getShort(aHeader, TC_HEADER_OFFSET_REQUIRED_VERSION);
boolean legacyVolume = requiredProgramVersion < TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION;
CRC32 crc = new CRC32();
crc.update(aHeader, HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE);
// Check CRC of the key set
if (ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_KEY_AREA_CRC) != (int)crc.getValue())
{
throw new RuntimeException("Bad master key CRC");
}
// Now we have the correct password, cipher, hash algorithm, and volume type
// Check the version required to handle this volume
if (requiredProgramVersion > VERSION_NUM)
{
// throw new RuntimeException("ERR_NEW_VERSION_REQUIRED");
}
// Hidden volume size (if any)
long hiddenVolumeSize = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE);
// Volume size
long volumeSize = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_VOLUME_SIZE);
// Encrypted area size and length
mVolumeDataAreaOffset = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_ENCRYPTED_AREA_START);
mVolumeDataAreaLength = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH);
// Flags
int headerFlags = ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_FLAGS);
// System.out.println("headerVersion="+headerVersion);
// System.out.println("requiredProgramVersion="+requiredProgramVersion);
// System.out.println("hiddenVolumeSize="+hiddenVolumeSize);
// System.out.println("VolumeSize="+volumeSize);
// System.out.println("EncryptedAreaStart="+mVolumeDataAreaOffset);
// System.out.println("EncryptedAreaLength="+mVolumeDataAreaLength);
// System.out.println("HeaderFlags="+headerFlags);
mCiphers = new Cipher[aCipherAlgorithms.length];
mTweakCiphers = new Cipher[aCipherAlgorithms.length];
for (int i = 0; i < aCipherAlgorithms.length; i++)
{
mCiphers[i] = getCipherInstance(aCipherAlgorithms[i]);
mTweakCiphers[i] = getCipherInstance(aCipherAlgorithms[i]);
mCiphers[i].engineInit(new SecretKey(aHeader, HEADER_MASTER_KEYDATA_OFFSET + 32 * i, 32));
mTweakCiphers[i].engineInit(new SecretKey(aHeader, HEADER_MASTER_KEYDATA_OFFSET + 32 * (i + aCipherAlgorithms.length), 32));
}
}
private static Cipher getCipherInstance(String aAlgorithm)
{
if (aAlgorithm.equals("aes"))
{
return new AES();
}
if (aAlgorithm.equals("serpent"))
{
return new Serpent();
}
if (aAlgorithm.equals("twofish"))
{
return new Twofish();
}
throw new RuntimeException();
}
private class VolumeHeaderDecoder implements Callable<Boolean>
{
private byte[] mHeader;
private CipherOption mCipherOption;
private DigestOption mDigestOption;
private byte[] mPassword;
VolumeHeaderDecoder(byte[] aHeader, CipherOption aCipherOption, DigestOption aDigestOption, byte[] aPassword)
{
mHeader = aHeader;
mCipherOption = aCipherOption;
mDigestOption = aDigestOption;
mPassword = aPassword;
}
@Override
public Boolean call()
{
try
{
HMAC hmac = new HMAC(mDigestOption.getDigestInstance(), mPassword);
int totalKeyLength = 32 * mCipherOption.mAlgorithms.length * 2;
byte[] salt = ByteArray.copy(mHeader, HEADER_SALT_OFFSET, PKCS5_SALT_SIZE);
byte[] keyBytes = PBKDF2.generateKeyBytes(hmac, salt, mDigestOption.mIterations, totalKeyLength);
XTS xts = new XTS(512);
for (int i = mCipherOption.mAlgorithms.length; --i >= 0;)
{
Cipher cipher = TrueCryptPageStore.getCipherInstance(mCipherOption.mAlgorithms[i]);
Cipher tweakCipher = TrueCryptPageStore.getCipherInstance(mCipherOption.mAlgorithms[i]);
cipher.engineInit(new SecretKey(keyBytes, 32 * i, 32));
tweakCipher.engineInit(new SecretKey(keyBytes, 32 * (i + mCipherOption.mAlgorithms.length), 32));
xts.decrypt(mHeader, PKCS5_SALT_SIZE, HEADER_ENCRYPTED_DATA_SIZE, 0, cipher, tweakCipher);
cipher.engineReset();
tweakCipher.engineReset();
}
if (ByteArray.BE.getInt(mHeader, TC_HEADER_OFFSET_MAGIC) == 0x54525545)
{
setup(mHeader, mCipherOption.mAlgorithms);
}
hmac.reset();
Arrays.fill(keyBytes, (byte)0);
Arrays.fill(mHeader, (byte)0);
Arrays.fill(mPassword, (byte)0);
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
return Boolean.TRUE;
}
}
@Override
public void read(long aPageIndex, byte[] aBuffer) throws IOException
{
read(aPageIndex, aBuffer, 0, aBuffer.length);
}
@Override
public void read(long aPageIndex, byte[] aBuffer, int aOffset, int aLength) throws IOException
{
long sectorIndex = mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE + aPageIndex;
mPageStore.read(sectorIndex, aBuffer, aOffset, aLength);
XTS xts = new XTS(512);
for (int j = 0; j < aLength / 512; j++)
{
for (int i = mCiphers.length; --i >= 0;)
{
xts.decrypt(aBuffer, aOffset + 512 * j, 512 + 0 * aLength, sectorIndex + j, mCiphers[i], mTweakCiphers[i]);
}
}
}
@Override
public void write(long aPageIndex, byte[] aBuffer) throws IOException
{
write(aPageIndex, aBuffer, 0, aBuffer.length);
}
@Override
public void write(long aPageIndex, byte[] aBuffer, int aOffset, int aLength) throws IOException
{
long sectorIndex = mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE + aPageIndex;
byte[] temp = new byte[aLength];
System.arraycopy(aBuffer, aOffset, temp, 0, aLength);
XTS xts = new XTS(512);
for (int i = 0; i < mCiphers.length; i++)
{
xts.encrypt(temp, 0, aLength, sectorIndex, mCiphers[i], mTweakCiphers[i]);
}
mPageStore.write(sectorIndex, temp, 0, aLength);
}
@Override
public int getPageSize() throws IOException
{
return ENCRYPTION_DATA_UNIT_SIZE;
}
@Override
public void close() throws IOException
{
if (mCiphers != null)
{
for (int i = 0; i < mCiphers.length; i++)
{
mCiphers[i].engineReset();
mTweakCiphers[i].engineReset();
}
}
mCiphers = null;
mTweakCiphers = null;
mVolumeDataAreaLength = 0;
mVolumeDataAreaOffset = 0;
if (mPageStore != null)
{
mPageStore.close();
}
mPageStore = null;
}
@Override
public void flush() throws IOException
{
mPageStore.flush();
}
@Override
public long getPageCount() throws IOException
{
return mPageStore.getPageCount() - mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE;
}
@Override
public void resize(long aPageCount) throws IOException
{
throw new UnsupportedOperationException("Not supported.");
}
private void format(Consumer<Long> aProgressCallback) throws IOException
{
int pageSize = getPageSize();
byte[] buffer = new byte[pageSize];
SecureRandom rnd = new SecureRandom();
XTS xts = new XTS(512);
for (long sectorIndex = 0, sz = getPageCount(); sectorIndex < sz; sectorIndex++)
{
rnd.nextBytes(buffer);
for (int i = 0; i < mCiphers.length; i++)
{
xts.encrypt(buffer, 0, pageSize, sectorIndex, mCiphers[i], mTweakCiphers[i]);
}
mPageStore.write(sectorIndex, buffer, 0, pageSize);
if (aProgressCallback != null)
{
aProgressCallback.accept(sectorIndex);
}
}
}
}
| terifan/TrueCrypt | src/org/terifan/truecrypt/TrueCryptPageStore.java | 4,673 | // Hidden volume size (if any) | line_comment | nl | package org.terifan.truecrypt;
import org.terifan.pagestore.PageStore;
import org.terifan.util.ByteArray;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.zip.CRC32;
public class TrueCryptPageStore implements PageStore, AutoCloseable
{
private final static int VERSION_NUM = 0x063a;
private final static int ENCRYPTION_DATA_UNIT_SIZE = 512;
private final static int PKCS5_SALT_SIZE = 64;
private final static int MASTER_KEYDATA_SIZE = 256;
private final static int VOLUME_HEADER_VERSION = 0x0004;
private final static int TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION = 0x0600;
private final static int TC_VOLUME_HEADER_EFFECTIVE_SIZE = 512;
private final static int TC_HEADER_OFFSET_MAGIC = 64;
private final static int TC_HEADER_OFFSET_VERSION = 68;
private final static int TC_HEADER_OFFSET_REQUIRED_VERSION = 70;
private final static int TC_HEADER_OFFSET_KEY_AREA_CRC = 72;
private final static int TC_HEADER_OFFSET_VOLUME_CREATION_TIME = 76;
private final static int TC_HEADER_OFFSET_MODIFICATION_TIME = 84;
private final static int TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE = 92;
private final static int TC_HEADER_OFFSET_VOLUME_SIZE = 100;
private final static int TC_HEADER_OFFSET_ENCRYPTED_AREA_START = 108;
private final static int TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH = 116;
private final static int TC_HEADER_OFFSET_FLAGS = 124;
private final static int TC_HEADER_OFFSET_HEADER_CRC = 252;
private final static int HEADER_SALT_OFFSET = 0;
private final static int HEADER_ENCRYPTED_DATA_OFFSET = PKCS5_SALT_SIZE;
private final static int HEADER_MASTER_KEYDATA_OFFSET = 256;
private final static int HEADER_ENCRYPTED_DATA_SIZE = (TC_VOLUME_HEADER_EFFECTIVE_SIZE - HEADER_ENCRYPTED_DATA_OFFSET);
public static enum CipherOption
{
AES("aes"),
SERPENT("serpent"),
TWOFISH("twofish"),
TWOFISH_AES("twofish", "aes"),
SERPENT_TWOFISH_AES("serpent", "twofish", "aes"),
AES_SERPENT("aes", "serpent"),
AES_TWOFISH_SERPENT("aes", "twofish", "serpent"),
SERPENT_TWOFISH("serpent", "twofish");
private final String[] mAlgorithms;
CipherOption(String... aAlgorithms)
{
mAlgorithms = aAlgorithms;
}
}
public static enum DigestOption
{
SHA512(1000),
RIPEMD160(2000),
WHIRLPOOL(1000);
private final int mIterations;
private DigestOption(int aIterations)
{
mIterations = aIterations;
}
MessageDigest getDigestInstance()
{
switch (this)
{
case SHA512:
return new SHA512();
case RIPEMD160:
return new RIPEMD160();
case WHIRLPOOL:
return new Whirlpool();
}
throw new RuntimeException();
}
}
private PageStore mPageStore;
private long mVolumeDataAreaOffset;
private long mVolumeDataAreaLength;
private Cipher[] mCiphers;
private Cipher[] mTweakCiphers;
private TrueCryptPageStore(PageStore aPageStore) throws IOException
{
if (aPageStore.getPageSize() != ENCRYPTION_DATA_UNIT_SIZE)
{
throw new IllegalArgumentException("Provided page store must have a " + ENCRYPTION_DATA_UNIT_SIZE + "-byte page size.");
}
mPageStore = aPageStore;
}
public static TrueCryptPageStore open(PageStore aPageStore, String aPassword) throws IOException
{
TrueCryptPageStore tc = new TrueCryptPageStore(aPageStore);
tc.readVolumeHeader(aPassword);
return tc;
}
public static TrueCryptPageStore create(PageStore aPageStore, long aPageCount, String aPassword, CipherOption aCipherOption, DigestOption aDigestOption, Consumer<Long> aProgressCallback) throws IOException
{
aPageStore.resize(aPageCount);
TrueCryptPageStore tc = new TrueCryptPageStore(aPageStore);
tc.format(aProgressCallback);
tc.writeVolumeHeader(aPassword);
return tc;
}
private void readVolumeHeader(String aPassword) throws IOException
{
byte[] headerBuffer = new byte[ENCRYPTION_DATA_UNIT_SIZE];
mPageStore.read(0, headerBuffer);
ArrayList<Callable<Boolean>> tasks = new ArrayList<>();
for (CipherOption cipher : CipherOption.values())
{
for (DigestOption digest : DigestOption.values())
{
VolumeHeaderDecoder task = new VolumeHeaderDecoder(headerBuffer.clone(), cipher, digest, aPassword.getBytes());
tasks.add(task);
}
}
int cpu = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(cpu);
try
{
pool.invokeAll(tasks);
}
catch (InterruptedException e)
{
}
pool.shutdown();
if (mCiphers == null)
{
throw new InvalidKeyException("Incorrect password or an unsupported file version.");
}
}
private void writeVolumeHeader(String aPassword)
{
}
private void setup(byte[] aHeader, String[] aCipherAlgorithms)
{
//Debug.hexDump(aHeader);
// Header version
int headerVersion = ByteArray.BE.getShort(aHeader, TC_HEADER_OFFSET_VERSION);
if (headerVersion > VOLUME_HEADER_VERSION)
{
//throw new RuntimeException("ERR_NEW_VERSION_REQUIRED " + headerVersion);
}
// Check CRC of the header fields
if (headerVersion >= 4)
{
CRC32 crc = new CRC32();
crc.update(aHeader, TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
if (ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_HEADER_CRC) != (int)crc.getValue())
{
throw new RuntimeException("Bad header CRC");
}
}
else
{
throw new RuntimeException("Bad version: " + headerVersion);
}
// Required program version
int requiredProgramVersion = ByteArray.BE.getShort(aHeader, TC_HEADER_OFFSET_REQUIRED_VERSION);
boolean legacyVolume = requiredProgramVersion < TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION;
CRC32 crc = new CRC32();
crc.update(aHeader, HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE);
// Check CRC of the key set
if (ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_KEY_AREA_CRC) != (int)crc.getValue())
{
throw new RuntimeException("Bad master key CRC");
}
// Now we have the correct password, cipher, hash algorithm, and volume type
// Check the version required to handle this volume
if (requiredProgramVersion > VERSION_NUM)
{
// throw new RuntimeException("ERR_NEW_VERSION_REQUIRED");
}
// Hidden volume<SUF>
long hiddenVolumeSize = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE);
// Volume size
long volumeSize = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_VOLUME_SIZE);
// Encrypted area size and length
mVolumeDataAreaOffset = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_ENCRYPTED_AREA_START);
mVolumeDataAreaLength = ByteArray.BE.getLong(aHeader, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH);
// Flags
int headerFlags = ByteArray.BE.getInt(aHeader, TC_HEADER_OFFSET_FLAGS);
// System.out.println("headerVersion="+headerVersion);
// System.out.println("requiredProgramVersion="+requiredProgramVersion);
// System.out.println("hiddenVolumeSize="+hiddenVolumeSize);
// System.out.println("VolumeSize="+volumeSize);
// System.out.println("EncryptedAreaStart="+mVolumeDataAreaOffset);
// System.out.println("EncryptedAreaLength="+mVolumeDataAreaLength);
// System.out.println("HeaderFlags="+headerFlags);
mCiphers = new Cipher[aCipherAlgorithms.length];
mTweakCiphers = new Cipher[aCipherAlgorithms.length];
for (int i = 0; i < aCipherAlgorithms.length; i++)
{
mCiphers[i] = getCipherInstance(aCipherAlgorithms[i]);
mTweakCiphers[i] = getCipherInstance(aCipherAlgorithms[i]);
mCiphers[i].engineInit(new SecretKey(aHeader, HEADER_MASTER_KEYDATA_OFFSET + 32 * i, 32));
mTweakCiphers[i].engineInit(new SecretKey(aHeader, HEADER_MASTER_KEYDATA_OFFSET + 32 * (i + aCipherAlgorithms.length), 32));
}
}
private static Cipher getCipherInstance(String aAlgorithm)
{
if (aAlgorithm.equals("aes"))
{
return new AES();
}
if (aAlgorithm.equals("serpent"))
{
return new Serpent();
}
if (aAlgorithm.equals("twofish"))
{
return new Twofish();
}
throw new RuntimeException();
}
private class VolumeHeaderDecoder implements Callable<Boolean>
{
private byte[] mHeader;
private CipherOption mCipherOption;
private DigestOption mDigestOption;
private byte[] mPassword;
VolumeHeaderDecoder(byte[] aHeader, CipherOption aCipherOption, DigestOption aDigestOption, byte[] aPassword)
{
mHeader = aHeader;
mCipherOption = aCipherOption;
mDigestOption = aDigestOption;
mPassword = aPassword;
}
@Override
public Boolean call()
{
try
{
HMAC hmac = new HMAC(mDigestOption.getDigestInstance(), mPassword);
int totalKeyLength = 32 * mCipherOption.mAlgorithms.length * 2;
byte[] salt = ByteArray.copy(mHeader, HEADER_SALT_OFFSET, PKCS5_SALT_SIZE);
byte[] keyBytes = PBKDF2.generateKeyBytes(hmac, salt, mDigestOption.mIterations, totalKeyLength);
XTS xts = new XTS(512);
for (int i = mCipherOption.mAlgorithms.length; --i >= 0;)
{
Cipher cipher = TrueCryptPageStore.getCipherInstance(mCipherOption.mAlgorithms[i]);
Cipher tweakCipher = TrueCryptPageStore.getCipherInstance(mCipherOption.mAlgorithms[i]);
cipher.engineInit(new SecretKey(keyBytes, 32 * i, 32));
tweakCipher.engineInit(new SecretKey(keyBytes, 32 * (i + mCipherOption.mAlgorithms.length), 32));
xts.decrypt(mHeader, PKCS5_SALT_SIZE, HEADER_ENCRYPTED_DATA_SIZE, 0, cipher, tweakCipher);
cipher.engineReset();
tweakCipher.engineReset();
}
if (ByteArray.BE.getInt(mHeader, TC_HEADER_OFFSET_MAGIC) == 0x54525545)
{
setup(mHeader, mCipherOption.mAlgorithms);
}
hmac.reset();
Arrays.fill(keyBytes, (byte)0);
Arrays.fill(mHeader, (byte)0);
Arrays.fill(mPassword, (byte)0);
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
return Boolean.TRUE;
}
}
@Override
public void read(long aPageIndex, byte[] aBuffer) throws IOException
{
read(aPageIndex, aBuffer, 0, aBuffer.length);
}
@Override
public void read(long aPageIndex, byte[] aBuffer, int aOffset, int aLength) throws IOException
{
long sectorIndex = mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE + aPageIndex;
mPageStore.read(sectorIndex, aBuffer, aOffset, aLength);
XTS xts = new XTS(512);
for (int j = 0; j < aLength / 512; j++)
{
for (int i = mCiphers.length; --i >= 0;)
{
xts.decrypt(aBuffer, aOffset + 512 * j, 512 + 0 * aLength, sectorIndex + j, mCiphers[i], mTweakCiphers[i]);
}
}
}
@Override
public void write(long aPageIndex, byte[] aBuffer) throws IOException
{
write(aPageIndex, aBuffer, 0, aBuffer.length);
}
@Override
public void write(long aPageIndex, byte[] aBuffer, int aOffset, int aLength) throws IOException
{
long sectorIndex = mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE + aPageIndex;
byte[] temp = new byte[aLength];
System.arraycopy(aBuffer, aOffset, temp, 0, aLength);
XTS xts = new XTS(512);
for (int i = 0; i < mCiphers.length; i++)
{
xts.encrypt(temp, 0, aLength, sectorIndex, mCiphers[i], mTweakCiphers[i]);
}
mPageStore.write(sectorIndex, temp, 0, aLength);
}
@Override
public int getPageSize() throws IOException
{
return ENCRYPTION_DATA_UNIT_SIZE;
}
@Override
public void close() throws IOException
{
if (mCiphers != null)
{
for (int i = 0; i < mCiphers.length; i++)
{
mCiphers[i].engineReset();
mTweakCiphers[i].engineReset();
}
}
mCiphers = null;
mTweakCiphers = null;
mVolumeDataAreaLength = 0;
mVolumeDataAreaOffset = 0;
if (mPageStore != null)
{
mPageStore.close();
}
mPageStore = null;
}
@Override
public void flush() throws IOException
{
mPageStore.flush();
}
@Override
public long getPageCount() throws IOException
{
return mPageStore.getPageCount() - mVolumeDataAreaOffset / ENCRYPTION_DATA_UNIT_SIZE;
}
@Override
public void resize(long aPageCount) throws IOException
{
throw new UnsupportedOperationException("Not supported.");
}
private void format(Consumer<Long> aProgressCallback) throws IOException
{
int pageSize = getPageSize();
byte[] buffer = new byte[pageSize];
SecureRandom rnd = new SecureRandom();
XTS xts = new XTS(512);
for (long sectorIndex = 0, sz = getPageCount(); sectorIndex < sz; sectorIndex++)
{
rnd.nextBytes(buffer);
for (int i = 0; i < mCiphers.length; i++)
{
xts.encrypt(buffer, 0, pageSize, sectorIndex, mCiphers[i], mTweakCiphers[i]);
}
mPageStore.write(sectorIndex, buffer, 0, pageSize);
if (aProgressCallback != null)
{
aProgressCallback.accept(sectorIndex);
}
}
}
}
|
120406_33 | package org.osgeo.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.osgeo.proj4j.datum.Datum;
import org.osgeo.proj4j.datum.Ellipsoid;
import org.osgeo.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*
*/
public class Registry {
public Registry() {
super();
initialize();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code)
{
for ( int i = 0; i < datums.length; i++ ) {
if ( datums[i].getCode().equals( code ) ) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name)
{
for ( int i = 0; i < ellipsoids.length; i++ ) {
if ( ellipsoids[i].shortName.equals( name ) ) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register( String name, Class cls, String description ) {
projRegistry.put( name, cls );
}
public Projection getProjection( String name ) {
// if ( projRegistry == null )
// initialize();
Class cls = (Class)projRegistry.get( name );
if ( cls != null ) {
try {
Projection projection = (Projection)cls.newInstance();
if ( projection != null )
projection.setName( name );
return projection;
}
catch ( IllegalAccessException e ) {
e.printStackTrace();
}
catch ( InstantiationException e ) {
e.printStackTrace();
}
}
return null;
}
@SuppressWarnings("unchecked")
private synchronized void initialize() {
// guard against race condition
if (projRegistry != null)
return;
projRegistry = new HashMap();
register( "aea", AlbersProjection.class, "Albers Equal Area" );
register( "aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant" );
register( "airy", AiryProjection.class, "Airy" );
register( "aitoff", AitoffProjection.class, "Aitoff" );
register( "alsk", Projection.class, "Mod. Stereographics of Alaska" );
register( "apian", Projection.class, "Apian Globular I" );
register( "august", AugustProjection.class, "August Epicycloidal" );
register( "bacon", Projection.class, "Bacon Globular" );
register( "bipc", BipolarProjection.class, "Bipolar conic of western hemisphere" );
register( "boggs", BoggsProjection.class, "Boggs Eumorphic" );
register( "bonne", BonneProjection.class, "Bonne (Werner lat_1=90)" );
register( "cass", CassiniProjection.class, "Cassini" );
register( "cc", CentralCylindricalProjection.class, "Central Cylindrical" );
register( "cea", Projection.class, "Equal Area Cylindrical" );
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
register( "collg", CollignonProjection.class, "Collignon" );
register( "crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)" );
register( "denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical" );
register( "eck1", Eckert1Projection.class, "Eckert I" );
register( "eck2", Eckert2Projection.class, "Eckert II" );
// register( "eck3", Eckert3Projection.class, "Eckert III" );
register( "eck4", Eckert4Projection.class, "Eckert IV" );
register( "eck5", Eckert5Projection.class, "Eckert V" );
register( "eck6", Eckert6Projection.class, "Eckert VI" );
register( "eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)" );
register( "eqdc", EquidistantConicProjection.class, "Equidistant Conic" );
register( "euler", EulerProjection.class, "Euler" );
register( "fahey", FaheyProjection.class, "Fahey" );
register( "fouc", FoucautProjection.class, "Foucaut" );
register( "fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal" );
register( "gall", GallProjection.class, "Gall (Gall Stereographic)" );
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
register( "gnom", GnomonicAzimuthalProjection.class, "Gnomonic" );
register( "goode", GoodeProjection.class, "Goode Homolosine" );
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
register( "hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff" );
register( "hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area" );
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
register( "kav5", KavraiskyVProjection.class, "Kavraisky V" );
// register( "kav7", Projection.class, "Kavraisky VII" );
// register( "labrd", Projection.class, "Laborde" );
register( "laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area" );
register( "lagrng", LagrangeProjection.class, "Lagrange" );
register( "larr", LarriveeProjection.class, "Larrivee" );
register( "lask", LaskowskiProjection.class, "Laskowski" );
register( "latlong", LongLatProjection.class, "Lat/Long" );
register( "longlat", LongLatProjection.class, "Lat/Long" );
register( "lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic" );
register( "leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic" );
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
register( "loxim", LoximuthalProjection.class, "Loximuthal" );
register( "lsat", LandsatProjection.class, "Space oblique for LANDSAT" );
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
register( "mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)" );
register( "mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic" );
register( "mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic" );
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
register( "merc", MercatorProjection.class, "Mercator" );
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
register( "mill", MillerProjection.class, "Miller Cylindrical" );
// register( "mpoly", Projection.class, "Modified Polyconic" );
register( "moll", MolleweideProjection.class, "Mollweide" );
register( "murd1", Murdoch1Projection.class, "Murdoch I" );
register( "murd2", Murdoch2Projection.class, "Murdoch II" );
register( "murd3", Murdoch3Projection.class, "Murdoch III" );
register( "nell", NellProjection.class, "Nell" );
// register( "nell_h", Projection.class, "Nell-Hammer" );
register( "nicol", NicolosiProjection.class, "Nicolosi Globular" );
register( "nsper", PerspectiveProjection.class, "Near-sided perspective" );
// register( "nzmg", Projection.class, "New Zealand Map Grid" );
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
register( "omerc", ObliqueMercatorProjection.class, "Oblique Mercator" );
// register( "ortel", Projection.class, "Ortelius Oval" );
register( "ortho", OrthographicAzimuthalProjection.class, "Orthographic" );
register( "pconic", PerspectiveConicProjection.class, "Perspective Conic" );
register( "poly", PolyconicProjection.class, "Polyconic (American)" );
// register( "putp1", Projection.class, "Putnins P1" );
register( "putp2", PutninsP2Projection.class, "Putnins P2" );
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
register( "putp4p", PutninsP4Projection.class, "Putnins P4'" );
register( "putp5", PutninsP5Projection.class, "Putnins P5" );
register( "putp5p", PutninsP5PProjection.class, "Putnins P5'" );
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
register( "qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic" );
register( "robin", RobinsonProjection.class, "Robinson" );
register( "rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic" );
register( "sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)" );
register( "somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator" );
register( "stere", StereographicAzimuthalProjection.class, "Stereographic" );
register( "sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative" );
register( "tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical" );
register( "tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area" );
// register( "tissot", TissotProjection.class, "Tissot Conic" );
register( "tmerc", TransverseMercatorProjection.class, "Transverse Mercator" );
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
register( "urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal" );
register( "utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)" );
register( "vandg", VanDerGrintenProjection.class, "van der Grinten (I)" );
// register( "vandg2", Projection.class, "van der Grinten II" );
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
register( "vitk1", VitkovskyProjection.class, "Vitkovsky I" );
register( "wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)" );
register( "wag2", Wagner2Projection.class, "Wagner II" );
register( "wag3", Wagner3Projection.class, "Wagner III" );
register( "wag4", Wagner4Projection.class, "Wagner IV" );
register( "wag5", Wagner5Projection.class, "Wagner V" );
// register( "wag6", Projection.class, "Wagner VI" );
register( "wag7", Wagner7Projection.class, "Wagner VII" );
register( "weren", WerenskioldProjection.class, "Werenskiold I" );
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
register( "wintri", WinkelTripelProjection.class, "Winkel Tripel" );
}
}
| terre-virtuelle/navisu | navisu-cartography/src/main/java/org/osgeo/proj4j/Registry.java | 5,422 | // register( "vandg2", Projection.class, "van der Grinten II" );
| line_comment | nl | package org.osgeo.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.osgeo.proj4j.datum.Datum;
import org.osgeo.proj4j.datum.Ellipsoid;
import org.osgeo.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*
*/
public class Registry {
public Registry() {
super();
initialize();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code)
{
for ( int i = 0; i < datums.length; i++ ) {
if ( datums[i].getCode().equals( code ) ) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name)
{
for ( int i = 0; i < ellipsoids.length; i++ ) {
if ( ellipsoids[i].shortName.equals( name ) ) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register( String name, Class cls, String description ) {
projRegistry.put( name, cls );
}
public Projection getProjection( String name ) {
// if ( projRegistry == null )
// initialize();
Class cls = (Class)projRegistry.get( name );
if ( cls != null ) {
try {
Projection projection = (Projection)cls.newInstance();
if ( projection != null )
projection.setName( name );
return projection;
}
catch ( IllegalAccessException e ) {
e.printStackTrace();
}
catch ( InstantiationException e ) {
e.printStackTrace();
}
}
return null;
}
@SuppressWarnings("unchecked")
private synchronized void initialize() {
// guard against race condition
if (projRegistry != null)
return;
projRegistry = new HashMap();
register( "aea", AlbersProjection.class, "Albers Equal Area" );
register( "aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant" );
register( "airy", AiryProjection.class, "Airy" );
register( "aitoff", AitoffProjection.class, "Aitoff" );
register( "alsk", Projection.class, "Mod. Stereographics of Alaska" );
register( "apian", Projection.class, "Apian Globular I" );
register( "august", AugustProjection.class, "August Epicycloidal" );
register( "bacon", Projection.class, "Bacon Globular" );
register( "bipc", BipolarProjection.class, "Bipolar conic of western hemisphere" );
register( "boggs", BoggsProjection.class, "Boggs Eumorphic" );
register( "bonne", BonneProjection.class, "Bonne (Werner lat_1=90)" );
register( "cass", CassiniProjection.class, "Cassini" );
register( "cc", CentralCylindricalProjection.class, "Central Cylindrical" );
register( "cea", Projection.class, "Equal Area Cylindrical" );
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
register( "collg", CollignonProjection.class, "Collignon" );
register( "crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)" );
register( "denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical" );
register( "eck1", Eckert1Projection.class, "Eckert I" );
register( "eck2", Eckert2Projection.class, "Eckert II" );
// register( "eck3", Eckert3Projection.class, "Eckert III" );
register( "eck4", Eckert4Projection.class, "Eckert IV" );
register( "eck5", Eckert5Projection.class, "Eckert V" );
register( "eck6", Eckert6Projection.class, "Eckert VI" );
register( "eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)" );
register( "eqdc", EquidistantConicProjection.class, "Equidistant Conic" );
register( "euler", EulerProjection.class, "Euler" );
register( "fahey", FaheyProjection.class, "Fahey" );
register( "fouc", FoucautProjection.class, "Foucaut" );
register( "fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal" );
register( "gall", GallProjection.class, "Gall (Gall Stereographic)" );
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
register( "gnom", GnomonicAzimuthalProjection.class, "Gnomonic" );
register( "goode", GoodeProjection.class, "Goode Homolosine" );
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
register( "hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff" );
register( "hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area" );
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
register( "kav5", KavraiskyVProjection.class, "Kavraisky V" );
// register( "kav7", Projection.class, "Kavraisky VII" );
// register( "labrd", Projection.class, "Laborde" );
register( "laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area" );
register( "lagrng", LagrangeProjection.class, "Lagrange" );
register( "larr", LarriveeProjection.class, "Larrivee" );
register( "lask", LaskowskiProjection.class, "Laskowski" );
register( "latlong", LongLatProjection.class, "Lat/Long" );
register( "longlat", LongLatProjection.class, "Lat/Long" );
register( "lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic" );
register( "leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic" );
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
register( "loxim", LoximuthalProjection.class, "Loximuthal" );
register( "lsat", LandsatProjection.class, "Space oblique for LANDSAT" );
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
register( "mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)" );
register( "mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic" );
register( "mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic" );
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
register( "merc", MercatorProjection.class, "Mercator" );
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
register( "mill", MillerProjection.class, "Miller Cylindrical" );
// register( "mpoly", Projection.class, "Modified Polyconic" );
register( "moll", MolleweideProjection.class, "Mollweide" );
register( "murd1", Murdoch1Projection.class, "Murdoch I" );
register( "murd2", Murdoch2Projection.class, "Murdoch II" );
register( "murd3", Murdoch3Projection.class, "Murdoch III" );
register( "nell", NellProjection.class, "Nell" );
// register( "nell_h", Projection.class, "Nell-Hammer" );
register( "nicol", NicolosiProjection.class, "Nicolosi Globular" );
register( "nsper", PerspectiveProjection.class, "Near-sided perspective" );
// register( "nzmg", Projection.class, "New Zealand Map Grid" );
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
register( "omerc", ObliqueMercatorProjection.class, "Oblique Mercator" );
// register( "ortel", Projection.class, "Ortelius Oval" );
register( "ortho", OrthographicAzimuthalProjection.class, "Orthographic" );
register( "pconic", PerspectiveConicProjection.class, "Perspective Conic" );
register( "poly", PolyconicProjection.class, "Polyconic (American)" );
// register( "putp1", Projection.class, "Putnins P1" );
register( "putp2", PutninsP2Projection.class, "Putnins P2" );
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
register( "putp4p", PutninsP4Projection.class, "Putnins P4'" );
register( "putp5", PutninsP5Projection.class, "Putnins P5" );
register( "putp5p", PutninsP5PProjection.class, "Putnins P5'" );
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
register( "qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic" );
register( "robin", RobinsonProjection.class, "Robinson" );
register( "rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic" );
register( "sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)" );
register( "somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator" );
register( "stere", StereographicAzimuthalProjection.class, "Stereographic" );
register( "sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative" );
register( "tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical" );
register( "tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area" );
// register( "tissot", TissotProjection.class, "Tissot Conic" );
register( "tmerc", TransverseMercatorProjection.class, "Transverse Mercator" );
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
register( "urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal" );
register( "utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)" );
register( "vandg", VanDerGrintenProjection.class, "van der Grinten (I)" );
// register( "vandg2",<SUF>
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
register( "vitk1", VitkovskyProjection.class, "Vitkovsky I" );
register( "wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)" );
register( "wag2", Wagner2Projection.class, "Wagner II" );
register( "wag3", Wagner3Projection.class, "Wagner III" );
register( "wag4", Wagner4Projection.class, "Wagner IV" );
register( "wag5", Wagner5Projection.class, "Wagner V" );
// register( "wag6", Projection.class, "Wagner VI" );
register( "wag7", Wagner7Projection.class, "Wagner VII" );
register( "weren", WerenskioldProjection.class, "Werenskiold I" );
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
register( "wintri", WinkelTripelProjection.class, "Winkel Tripel" );
}
}
|
17427_1 | class Student {
// Schrijf een functie last(int[] xs) die gegeven een array xs het laatste element ervan teruggeeft.
// Je mag ervan uitgaan dat xs minstens één element bevat.
public int last(int[] xs){
return xs[xs.length - 1];
}
}
| testMJTesting/mj_test1 | 03-arrays/Student.java | 82 | // Je mag ervan uitgaan dat xs minstens één element bevat. | line_comment | nl | class Student {
// Schrijf een functie last(int[] xs) die gegeven een array xs het laatste element ervan teruggeeft.
// Je mag<SUF>
public int last(int[] xs){
return xs[xs.length - 1];
}
}
|
21047_3 | public class Student {
// LOOPS ==============================================
// Je belegt €1000 tegen 5%. Schrijf een functie invest(goal) die gegeven een doelbedrag goal,
// uitrekent hoeveel jaar het duur eer je €1000 gegroeid zijn tot goal.
// Ga ervan uit dat de intrest telkens toegevoegd wordt op het einde van elk jaar.
//
// Je kan dit in principe met logaritmes oplossen, maar dit valt buiten het bereik van dit vak.
// Voor deze oefening is het de bedoeling dat je een lus gebruikt om herhaaldelijk 5% toe te voegen
// aan het initieel bedrag tot het voldoende gegroeid is.
} | testMJTesting/mj_test4 | 04-loops/Student.java | 193 | // Je kan dit in principe met logaritmes oplossen, maar dit valt buiten het bereik van dit vak. | line_comment | nl | public class Student {
// LOOPS ==============================================
// Je belegt €1000 tegen 5%. Schrijf een functie invest(goal) die gegeven een doelbedrag goal,
// uitrekent hoeveel jaar het duur eer je €1000 gegroeid zijn tot goal.
// Ga ervan uit dat de intrest telkens toegevoegd wordt op het einde van elk jaar.
//
// Je kan<SUF>
// Voor deze oefening is het de bedoeling dat je een lus gebruikt om herhaaldelijk 5% toe te voegen
// aan het initieel bedrag tot het voldoende gegroeid is.
} |
44409_3 | package tjesmits.android.avans.nl.bolbrowser.api;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import tjesmits.android.avans.nl.bolbrowser.api.interfaces.OnProductAvailable;
import tjesmits.android.avans.nl.bolbrowser.domain.Product;
/**
* Created by Tom Smits on 9-3-2018.
*/
public class ProductTask extends AsyncTask<String, Void, String> {
// Callback
private OnProductAvailable listener = null;
// Statics
private static final String TAG = ProductTask.class.getSimpleName();
// Constructor, set listener
public ProductTask(OnProductAvailable listener) {
this.listener = listener;
}
/**
* doInBackground is de methode waarin de aanroep naar een service op
* het Internet gedaan wordt.
*
* @param params
* @return
*/
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
int responsCode = -1;
// De URL die we via de .execute() meegeleverd krijgen
String personUrl = params[0];
// Het resultaat dat we gaan retourneren
String response = "";
Log.i(TAG, "doInBackground - " + personUrl);
try {
// Maak een URL object
URL url = new URL(personUrl);
// Open een connection op de URL
URLConnection urlConnection = url.openConnection();
if (!(urlConnection instanceof HttpURLConnection)) {
return null;
}
// Initialiseer een HTTP connectie
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
httpConnection.setAllowUserInteraction(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestMethod("GET");
// Voer het request uit via de HTTP connectie op de URL
httpConnection.connect();
// Kijk of het gelukt is door de response code te checken
responsCode = httpConnection.getResponseCode();
if (responsCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConnection.getInputStream();
response = getStringFromInputStream(inputStream);
// Log.i(TAG, "doInBackground response = " + response);
} else {
Log.e(TAG, "Error, invalid response");
}
} catch (MalformedURLException e) {
Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage());
return null;
} catch (IOException e) {
Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage());
return null;
}
// Hier eindigt deze methode.
// Het resultaat gaat naar de onPostExecute methode.
return response;
}
/**
* onPostExecute verwerkt het resultaat uit de doInBackground methode.
*
* @param response
*/
protected void onPostExecute(String response) {
Log.i(TAG, "onPostExecute " + response);
// Check of er een response is
if(response == null || response == "") {
Log.e(TAG, "onPostExecute kreeg een lege response!");
return;
}
// Het resultaat is in ons geval een stuk tekst in JSON formaat.
// Daar moeten we de info die we willen tonen uit filteren (parsen).
// Dat kan met een JSONObject.
JSONObject jsonObject;
try {
// Top level json object
jsonObject = new JSONObject(response);
// Get all users and start looping
JSONArray productsArray = jsonObject.getJSONArray("products");
for(int idx = 0; idx < productsArray.length(); idx++) {
// array level objects and get user
JSONObject productObject = productsArray.getJSONObject(idx);
// Get title, first and last name
String id = productObject.getString("id");
String title = productObject.getString("title");
String tag = null;
if (productObject.has("summary")) {
tag = productObject.getString("summary");
}
else {
tag = productObject.getString("specsTag");
}
int rating = productObject.getInt("rating");
String description = productObject.getString("longDescription");
// Get the price of product and formats text.
String price = productObject.getJSONObject("offerData").getJSONArray("offers").getJSONObject(0).getString("price");
String finalPrice = null;
if (price.endsWith(".0")) {
finalPrice = price.replace(".0", ",-");
}
else if (price.matches("(?i).*.*"))
{
finalPrice = price.replace(".", ",");
}
Log.i(TAG, "Got product " + id + " " + title);
// Get image url
String imageThumbURL = productObject.getJSONArray("images").getJSONObject(0).getString("url");
String imageURL = productObject.getJSONArray("images").getJSONObject(1).getString("url");
Log.i(TAG, imageURL);
// Create new Product object
// Builder Design Pattern
Product product = new Product.ProductBuilder(title, tag, rating, finalPrice)
.setID(id)
.setDescription(description)
.setImageURL(imageThumbURL, imageURL)
.build();
//
// call back with new product data
//
listener.OnProductAvailable(product);
}
} catch( JSONException ex) {
Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage());
}
}
//
// convert InputStream to String
//
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
} | teumaas/BolBrowser | app/src/main/java/tjesmits/android/avans/nl/bolbrowser/api/ProductTask.java | 1,784 | // De URL die we via de .execute() meegeleverd krijgen | line_comment | nl | package tjesmits.android.avans.nl.bolbrowser.api;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import tjesmits.android.avans.nl.bolbrowser.api.interfaces.OnProductAvailable;
import tjesmits.android.avans.nl.bolbrowser.domain.Product;
/**
* Created by Tom Smits on 9-3-2018.
*/
public class ProductTask extends AsyncTask<String, Void, String> {
// Callback
private OnProductAvailable listener = null;
// Statics
private static final String TAG = ProductTask.class.getSimpleName();
// Constructor, set listener
public ProductTask(OnProductAvailable listener) {
this.listener = listener;
}
/**
* doInBackground is de methode waarin de aanroep naar een service op
* het Internet gedaan wordt.
*
* @param params
* @return
*/
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
int responsCode = -1;
// De URL<SUF>
String personUrl = params[0];
// Het resultaat dat we gaan retourneren
String response = "";
Log.i(TAG, "doInBackground - " + personUrl);
try {
// Maak een URL object
URL url = new URL(personUrl);
// Open een connection op de URL
URLConnection urlConnection = url.openConnection();
if (!(urlConnection instanceof HttpURLConnection)) {
return null;
}
// Initialiseer een HTTP connectie
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
httpConnection.setAllowUserInteraction(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestMethod("GET");
// Voer het request uit via de HTTP connectie op de URL
httpConnection.connect();
// Kijk of het gelukt is door de response code te checken
responsCode = httpConnection.getResponseCode();
if (responsCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConnection.getInputStream();
response = getStringFromInputStream(inputStream);
// Log.i(TAG, "doInBackground response = " + response);
} else {
Log.e(TAG, "Error, invalid response");
}
} catch (MalformedURLException e) {
Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage());
return null;
} catch (IOException e) {
Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage());
return null;
}
// Hier eindigt deze methode.
// Het resultaat gaat naar de onPostExecute methode.
return response;
}
/**
* onPostExecute verwerkt het resultaat uit de doInBackground methode.
*
* @param response
*/
protected void onPostExecute(String response) {
Log.i(TAG, "onPostExecute " + response);
// Check of er een response is
if(response == null || response == "") {
Log.e(TAG, "onPostExecute kreeg een lege response!");
return;
}
// Het resultaat is in ons geval een stuk tekst in JSON formaat.
// Daar moeten we de info die we willen tonen uit filteren (parsen).
// Dat kan met een JSONObject.
JSONObject jsonObject;
try {
// Top level json object
jsonObject = new JSONObject(response);
// Get all users and start looping
JSONArray productsArray = jsonObject.getJSONArray("products");
for(int idx = 0; idx < productsArray.length(); idx++) {
// array level objects and get user
JSONObject productObject = productsArray.getJSONObject(idx);
// Get title, first and last name
String id = productObject.getString("id");
String title = productObject.getString("title");
String tag = null;
if (productObject.has("summary")) {
tag = productObject.getString("summary");
}
else {
tag = productObject.getString("specsTag");
}
int rating = productObject.getInt("rating");
String description = productObject.getString("longDescription");
// Get the price of product and formats text.
String price = productObject.getJSONObject("offerData").getJSONArray("offers").getJSONObject(0).getString("price");
String finalPrice = null;
if (price.endsWith(".0")) {
finalPrice = price.replace(".0", ",-");
}
else if (price.matches("(?i).*.*"))
{
finalPrice = price.replace(".", ",");
}
Log.i(TAG, "Got product " + id + " " + title);
// Get image url
String imageThumbURL = productObject.getJSONArray("images").getJSONObject(0).getString("url");
String imageURL = productObject.getJSONArray("images").getJSONObject(1).getString("url");
Log.i(TAG, imageURL);
// Create new Product object
// Builder Design Pattern
Product product = new Product.ProductBuilder(title, tag, rating, finalPrice)
.setID(id)
.setDescription(description)
.setImageURL(imageThumbURL, imageURL)
.build();
//
// call back with new product data
//
listener.OnProductAvailable(product);
}
} catch( JSONException ex) {
Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage());
}
}
//
// convert InputStream to String
//
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
} |
18288_9 | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Centuries of Rage 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module geladen, starten
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
| tfg13/Centuries-of-Rage | src/de/_13ducks/cor/game/server/ServerCore.java | 3,501 | // Alle Module geladen, starten | line_comment | nl | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Centuries of Rage 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module<SUF>
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
|
109118_5 | package de._13ducks.spacebatz.server.gamelogic;
import de._13ducks.spacebatz.server.data.Client;
import de._13ducks.spacebatz.server.data.quests.Quest;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Verwaltet die Quests.
*
* @author Tobias Fleig <[email protected]>
*/
public class QuestManager {
/**
* Alle aktiven Quests.
*/
private ArrayList<Quest> activeQuests = new ArrayList<>();
/**
* Quests, die im nächsten Tick hinzugefügt werden.
* Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden.
*/
private ArrayList<Quest> newQuests = new ArrayList<>();
/**
* Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests.
*/
public void tick() {
// Neue Quests hinzufügen
activeQuests.addAll(newQuests);
for (Quest q : newQuests) {
// An Client senden
if (!q.isHidden()) {
STC_NEW_QUEST.sendQuest(q);
}
}
newQuests.clear();
Iterator<Quest> iter = activeQuests.iterator();
while (iter.hasNext()) {
Quest quest = iter.next();
try {
// Quest ticken, dann Status abfragen
quest.tick();
int state = quest.check();
// Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht
if (state != -1) {
if (state == Quest.STATE_RUNNING) {
// Nichts spannendes, weiterlaufen lassen
continue;
}
if (state == Quest.STATE_COMPLETED) {
// Erfolgreich
//@TODO: Belohnung verteilen?
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed.");
} else if (state == Quest.STATE_FAILED) {
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed.");
} else if (state == Quest.STATE_ABORTED) {
System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons...");
}
// Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss
iter.remove();
// Client quest entfernen lassen
STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state);
}
} catch (Exception ex) {
// Quest ist abgestürzt - Loggen und Quest löschen
iter.remove();
System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:");
ex.printStackTrace();
}
}
}
/**
* Fügt einen neuen Quest hinzu.
* Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen.
*
* @param quest der neue Quest, läuft ab dem nächsten Tick mit
*/
public void addQuest(Quest quest) {
newQuests.add(quest);
}
/**
* Aufrufen, wenn ein neuer Client eingefügt wurde.
* Sendet alle aktiven, nicht geheimen Quests an den neuen.
*
* @param client
*/
void newClient(Client client) {
for (Quest quest : activeQuests) {
if (!quest.isHidden()) {
STC_NEW_QUEST.sendQuest(quest);
}
}
}
}
| tfg13/spacebatz | src/de/_13ducks/spacebatz/server/gamelogic/QuestManager.java | 1,107 | // An Client senden | line_comment | nl | package de._13ducks.spacebatz.server.gamelogic;
import de._13ducks.spacebatz.server.data.Client;
import de._13ducks.spacebatz.server.data.quests.Quest;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Verwaltet die Quests.
*
* @author Tobias Fleig <[email protected]>
*/
public class QuestManager {
/**
* Alle aktiven Quests.
*/
private ArrayList<Quest> activeQuests = new ArrayList<>();
/**
* Quests, die im nächsten Tick hinzugefügt werden.
* Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden.
*/
private ArrayList<Quest> newQuests = new ArrayList<>();
/**
* Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests.
*/
public void tick() {
// Neue Quests hinzufügen
activeQuests.addAll(newQuests);
for (Quest q : newQuests) {
// An Client<SUF>
if (!q.isHidden()) {
STC_NEW_QUEST.sendQuest(q);
}
}
newQuests.clear();
Iterator<Quest> iter = activeQuests.iterator();
while (iter.hasNext()) {
Quest quest = iter.next();
try {
// Quest ticken, dann Status abfragen
quest.tick();
int state = quest.check();
// Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht
if (state != -1) {
if (state == Quest.STATE_RUNNING) {
// Nichts spannendes, weiterlaufen lassen
continue;
}
if (state == Quest.STATE_COMPLETED) {
// Erfolgreich
//@TODO: Belohnung verteilen?
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed.");
} else if (state == Quest.STATE_FAILED) {
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed.");
} else if (state == Quest.STATE_ABORTED) {
System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons...");
}
// Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss
iter.remove();
// Client quest entfernen lassen
STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state);
}
} catch (Exception ex) {
// Quest ist abgestürzt - Loggen und Quest löschen
iter.remove();
System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:");
ex.printStackTrace();
}
}
}
/**
* Fügt einen neuen Quest hinzu.
* Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen.
*
* @param quest der neue Quest, läuft ab dem nächsten Tick mit
*/
public void addQuest(Quest quest) {
newQuests.add(quest);
}
/**
* Aufrufen, wenn ein neuer Client eingefügt wurde.
* Sendet alle aktiven, nicht geheimen Quests an den neuen.
*
* @param client
*/
void newClient(Client client) {
for (Quest quest : activeQuests) {
if (!quest.isHidden()) {
STC_NEW_QUEST.sendQuest(quest);
}
}
}
}
|
55954_17 | /*
* @Copyright 2018-2023 HardBackNutter
* @License GNU General Public License
*
* This file is part of NeverTooManyBooks.
*
* NeverTooManyBooks is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NeverTooManyBooks 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>.
*/
package com.hardbacknutter.nevertoomanybooks.searchengines.kbnl;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.hardbacknutter.nevertoomanybooks.database.DBKey;
import com.hardbacknutter.nevertoomanybooks.entities.Author;
import com.hardbacknutter.nevertoomanybooks.entities.Book;
import com.hardbacknutter.nevertoomanybooks.entities.Publisher;
import com.hardbacknutter.nevertoomanybooks.entities.Series;
import com.hardbacknutter.nevertoomanybooks.searchengines.SearchEngineUtils;
import org.xml.sax.SAXException;
class KbNlBookHandler
extends KbNlHandlerBase {
private static final Pattern ISBN_BOUNDARY_PATTERN = Pattern.compile("[;)]");
@NonNull
private final KbNlSearchEngine searchEngine;
@Nullable
private String tmpSeriesNr;
/**
* Constructor.
*
* @param kbNlSearchEngine engine
* @param data Book to update
*/
KbNlBookHandler(@NonNull final KbNlSearchEngine kbNlSearchEngine,
@NonNull final Book data) {
super(data);
searchEngine = kbNlSearchEngine;
}
@Override
public void startDocument()
throws SAXException {
super.startDocument();
tmpSeriesNr = null;
}
@Override
public void endDocument()
throws SAXException {
super.endDocument();
if (tmpSeriesNr != null) {
final String title = book.getString(DBKey.TITLE, null);
// should never happen, but paranoia...
if (title != null && !title.isBlank()) {
final Series series = Series.from(title, tmpSeriesNr);
book.add(series);
}
}
// There is no language field; e.g. french books data is the same as dutch ones.
// just add Dutch and hope for the best.
if (!book.isEmpty() && !book.contains(DBKey.LANGUAGE)) {
book.putString(DBKey.LANGUAGE, "nld");
}
}
/**
* Labels for both Dutch (default) and English are listed.
* <p>
* Note that "Colorist" is also used in Dutch.
*
* @param currentLabel the current {@code labelledLabel}
* @param currentData content of {@code labelledData}
*/
protected void processEntry(@NonNull final String currentLabel,
@NonNull final List<String> currentData) {
switch (currentLabel) {
case "Title":
case "Titel":
processTitle(currentData);
break;
case "Author":
case "Auteur":
processAuthor(currentData, Author.TYPE_WRITER);
break;
case "Collaborator":
case "Medewerker":
processAuthor(currentData, Author.TYPE_CONTRIBUTOR);
break;
case "Artist":
case "Kunstenaar":
// artist is for comics etc
case "Illustrator":
// illustrator (label is same in dutch) is for books
// Just put them both down as artists
processAuthor(currentData, Author.TYPE_ARTIST);
break;
case "Colorist":
processAuthor(currentData, Author.TYPE_COLORIST);
break;
case "Translator":
case "Vertaler":
processAuthor(currentData, Author.TYPE_TRANSLATOR);
break;
case "Series":
case "Reeks":
processSeries(currentData);
break;
case "Part(s)":
case "Deel / delen":
processSeriesNumber(currentData);
break;
case "Publisher":
case "Uitgever":
processPublisher(currentData);
break;
case "Year":
case "Jaar":
processDatePublished(currentData);
break;
case "Extent":
case "Omvang":
processPages(currentData);
break;
case "ISBN":
processIsbn(currentData);
break;
case "Illustration":
case "Illustratie":
processIllustration(currentData);
break;
case "Size":
case "Formaat":
// seen, but skipped for now; it's one dimension, presumably the height.
// Formaat: 30 cm
break;
case "Physical information":
case "Fysieke informatie":
// "1 file (PDF)"
break;
case "Editie":
// [2e dr.]
break;
case "Contains":
case "Bevat / omvat":
processDescription(currentData);
break;
case "Note":
case "Annotatie":
// Note/Annotatie seems to have been replaced on newer books by
case "Annotation edition":
case "Annotatie editie":
// Omslag vermeldt: K2
//Opl. van 750 genummerde ex
//Vert. van: Cromwell Stone. - Delcourt, cop. 1993
break;
//case "Note": in english used a second time for a different field. Unique in dutch.
case "Noot":
break;
case "Annex":
case "Bijlage":
// kleurenprent van oorspr. cover
break;
case "Subject heading Depot":
case "Trefwoord Depot":
// not used
case "Request number":
case "Aanvraagnummer":
// not used
case "Loan indication":
case "Uitleenindicatie":
// not used
case "Lending information":
case "Aanvraaginfo":
// not used
break;
case "Manufacturer":
case "Vervaardiger":
// not used
break;
default:
// ignore
break;
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>De</psi:text>
* <psi:text href="CLK?IKT=4&TRM=Foundation">Foundation</psi:text>
* <psi:text>/ Isaac Asimov ; [vert. uit het Engels door Jack Kröner]</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=422449059&REC=*">
* De buitengewone reis / Silvio Camboni
* </psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processTitle(@NonNull final Iterable<String> currentData) {
final String[] cleanedData = String.join(" ", currentData).split("/");
book.putString(DBKey.TITLE, cleanedData[0].strip());
// It's temping to decode [1], as this is the author as it appears on the cover,
// but the data has proven to be very unstructured and mostly unusable.
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068561504">Isaak Judovič Ozimov (1920-1992)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068870728">Jean-Pol is Jean-Paul Van den Broeck</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=070047596">Dirk Stallaert (1955-)</psi:text>
* <psi:text>;</psi:text>
* <psi:text href="REL?PPN=073286796">Leo Loedts</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068852002">Ruurd Feenstra (1904-1974)
* (ISNI 0000 0000 2173 3650) </psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
*
*
* <p>
* Note that the author name in the above example can be the "actual" name, and not
* the publicly known/used name, i.e. in this case "Isaac Asimov"
* The 2nd sample shows how the site is creative (hum) about authors using pen-names.
* The 3rd example has a list of authors for the same author type.
* The 4th sample shows that dates and other info can be added
* <p>
* Getting author names:
* http://opc4.kb.nl/DB=1/SET=1/TTL=1/REL?PPN=068561504
*
* @param currentData content of {@code labelledData}
* @param type the author type
*/
private void processAuthor(@NonNull final Iterable<String> currentData,
@Author.Type final int type) {
for (final String text : currentData) {
// remove any "(..)" parts in the name
final String cleanedString = text.split("\\(")[0].strip();
// reject separators as for example: <psi:text>;</psi:text>
if (cleanedString.length() == 1) {
return;
}
searchEngine.processAuthor(Author.from(cleanedString), type, book);
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=841288933&REC=*">Foundation-trilogie</psi:text>
* <psi:text>;</psi:text>
* <psi:text href="CLK?IKT=12&TRM=841288933&REC=*">dl. 1</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=851863523&REC=*">Discus-serie</psi:text>
* <psi:text>; </psi:text>
* <psi:text href="CLK?IKT=12&TRM=821611178&REC=*">Kluitman jeugdserie</psi:text>
* <psi:text> ; </psi:text>
* <psi:text href="CLK?IKT=12&TRM=821611178&REC=*">J 1247</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processSeries(@NonNull final List<String> currentData) {
book.add(Series.from(currentData.get(0)));
// the number part is totally unstructured
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>Deel 1 / blah</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processSeriesNumber(@NonNull final List<String> currentData) {
// This element is listed BEFORE the Series ("reeks") itself so store it tmp.
// Note it's often missing altogether
final String[] nrStr = currentData.get(0).split("/")[0].split(" ");
if (nrStr.length > 1) {
tmpSeriesNr = nrStr[1];
} else {
tmpSeriesNr = nrStr[0];
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text mark="highlight">90-229-5335-1</psi:text>
* <psi:text>(geb.)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text mark="highlight">978-94-6373145-4</psi:text>
* <psi:text> (paperback)</psi:text>
* </psi:line>
* <psi:line>
* <psi:text> </psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text> (Geb.; f. 4,50)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>2-256-90374-5 : 40.00F</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text> : 42.00F</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processIsbn(@NonNull final List<String> currentData) {
for (final String text : currentData) {
if (Character.isDigit(text.charAt(0))) {
if (!book.contains(DBKey.BOOK_ISBN)) {
final String digits = SearchEngineUtils.isbn(text.split(":")[0]);
// Do a crude test on the length and hope for the best
// (don't do a full ISBN test here, no need)
if (digits != null && (digits.length() == 10 || digits.length() == 13)) {
book.putString(DBKey.BOOK_ISBN, digits);
}
}
} else if (text.charAt(0) == '(') {
if (!book.contains(DBKey.FORMAT)) {
// Skip the 1th bracket, and split either on closing or on semicolon
final String value = ISBN_BOUNDARY_PATTERN.split(text.substring(1))[0].strip();
if (!value.isBlank()) {
book.putString(DBKey.FORMAT, value);
}
}
}
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=3003&TRM=Breda">Breda</psi:text>
* <psi:text> : </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Dark">Dark</psi:text>
* <psi:text> </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Dragon">Dragon</psi:text>
* <psi:text> </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Books">Books</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=3003&TRM=Utrecht">Utrecht</psi:text>
* <psi:text>[</psi:text>
* <psi:text href="CLK?IKT=3003&TRM=etc.">etc.</psi:text>
* <psi:text>] :</psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Bruna">Bruna</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processPublisher(@NonNull final List<String> currentData) {
String publisherName = currentData.stream()
.filter(name -> !name.isEmpty())
.collect(Collectors.joining(" "));
// the part before the ":" is (usually?) the city. 2nd part is the publisher
if (publisherName.contains(":")) {
publisherName = publisherName.split(":")[1].strip();
}
book.add(Publisher.from(publisherName));
}
/**
* Process a year field. Once again the data is not structured, but at least
* it's guessable. Some examples:
*
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>1983</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>[2019]</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>cop. 1986</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>c1977, cover 1978</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processDatePublished(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.BOOK_PUBLICATION__DATE)) {
// Grab the first bit before a comma, and strip it for digits + hope for the best
final String year = SearchEngineUtils.digits(currentData.get(0).split(",")[0]);
if (!year.isEmpty()) {
try {
book.setPublicationDate(Integer.parseInt(year));
} catch (@NonNull final NumberFormatException ignore) {
// ignore
}
}
}
}
/**
* Process the number-of-pages field. Once again the data is not structured, but at least
* it's guessable. Some examples:
*
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>48 pagina's</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>156 p</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processPages(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.PAGE_COUNT)) {
try {
final String cleanedString = currentData.get(0).split(" ")[0];
final int pages = Integer.parseInt(cleanedString);
book.putString(DBKey.PAGE_COUNT, String.valueOf(pages));
} catch (@NonNull final NumberFormatException e) {
// use source
book.putString(DBKey.PAGE_COUNT, currentData.get(0));
}
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>gekleurde illustraties</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>zw. ill</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processIllustration(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.COLOR)) {
book.putString(DBKey.COLOR, currentData.get(0));
}
}
private void processDescription(final List<String> currentData) {
book.putString(DBKey.DESCRIPTION, currentData
.stream()
.filter(name -> !name.isEmpty())
.collect(Collectors.joining(" ")));
}
}
| tfonteyn/NeverTooManyBooks | app/src/main/java/com/hardbacknutter/nevertoomanybooks/searchengines/kbnl/KbNlBookHandler.java | 6,088 | // kleurenprent van oorspr. cover | line_comment | nl | /*
* @Copyright 2018-2023 HardBackNutter
* @License GNU General Public License
*
* This file is part of NeverTooManyBooks.
*
* NeverTooManyBooks is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NeverTooManyBooks 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>.
*/
package com.hardbacknutter.nevertoomanybooks.searchengines.kbnl;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.hardbacknutter.nevertoomanybooks.database.DBKey;
import com.hardbacknutter.nevertoomanybooks.entities.Author;
import com.hardbacknutter.nevertoomanybooks.entities.Book;
import com.hardbacknutter.nevertoomanybooks.entities.Publisher;
import com.hardbacknutter.nevertoomanybooks.entities.Series;
import com.hardbacknutter.nevertoomanybooks.searchengines.SearchEngineUtils;
import org.xml.sax.SAXException;
class KbNlBookHandler
extends KbNlHandlerBase {
private static final Pattern ISBN_BOUNDARY_PATTERN = Pattern.compile("[;)]");
@NonNull
private final KbNlSearchEngine searchEngine;
@Nullable
private String tmpSeriesNr;
/**
* Constructor.
*
* @param kbNlSearchEngine engine
* @param data Book to update
*/
KbNlBookHandler(@NonNull final KbNlSearchEngine kbNlSearchEngine,
@NonNull final Book data) {
super(data);
searchEngine = kbNlSearchEngine;
}
@Override
public void startDocument()
throws SAXException {
super.startDocument();
tmpSeriesNr = null;
}
@Override
public void endDocument()
throws SAXException {
super.endDocument();
if (tmpSeriesNr != null) {
final String title = book.getString(DBKey.TITLE, null);
// should never happen, but paranoia...
if (title != null && !title.isBlank()) {
final Series series = Series.from(title, tmpSeriesNr);
book.add(series);
}
}
// There is no language field; e.g. french books data is the same as dutch ones.
// just add Dutch and hope for the best.
if (!book.isEmpty() && !book.contains(DBKey.LANGUAGE)) {
book.putString(DBKey.LANGUAGE, "nld");
}
}
/**
* Labels for both Dutch (default) and English are listed.
* <p>
* Note that "Colorist" is also used in Dutch.
*
* @param currentLabel the current {@code labelledLabel}
* @param currentData content of {@code labelledData}
*/
protected void processEntry(@NonNull final String currentLabel,
@NonNull final List<String> currentData) {
switch (currentLabel) {
case "Title":
case "Titel":
processTitle(currentData);
break;
case "Author":
case "Auteur":
processAuthor(currentData, Author.TYPE_WRITER);
break;
case "Collaborator":
case "Medewerker":
processAuthor(currentData, Author.TYPE_CONTRIBUTOR);
break;
case "Artist":
case "Kunstenaar":
// artist is for comics etc
case "Illustrator":
// illustrator (label is same in dutch) is for books
// Just put them both down as artists
processAuthor(currentData, Author.TYPE_ARTIST);
break;
case "Colorist":
processAuthor(currentData, Author.TYPE_COLORIST);
break;
case "Translator":
case "Vertaler":
processAuthor(currentData, Author.TYPE_TRANSLATOR);
break;
case "Series":
case "Reeks":
processSeries(currentData);
break;
case "Part(s)":
case "Deel / delen":
processSeriesNumber(currentData);
break;
case "Publisher":
case "Uitgever":
processPublisher(currentData);
break;
case "Year":
case "Jaar":
processDatePublished(currentData);
break;
case "Extent":
case "Omvang":
processPages(currentData);
break;
case "ISBN":
processIsbn(currentData);
break;
case "Illustration":
case "Illustratie":
processIllustration(currentData);
break;
case "Size":
case "Formaat":
// seen, but skipped for now; it's one dimension, presumably the height.
// Formaat: 30 cm
break;
case "Physical information":
case "Fysieke informatie":
// "1 file (PDF)"
break;
case "Editie":
// [2e dr.]
break;
case "Contains":
case "Bevat / omvat":
processDescription(currentData);
break;
case "Note":
case "Annotatie":
// Note/Annotatie seems to have been replaced on newer books by
case "Annotation edition":
case "Annotatie editie":
// Omslag vermeldt: K2
//Opl. van 750 genummerde ex
//Vert. van: Cromwell Stone. - Delcourt, cop. 1993
break;
//case "Note": in english used a second time for a different field. Unique in dutch.
case "Noot":
break;
case "Annex":
case "Bijlage":
// kleurenprent van<SUF>
break;
case "Subject heading Depot":
case "Trefwoord Depot":
// not used
case "Request number":
case "Aanvraagnummer":
// not used
case "Loan indication":
case "Uitleenindicatie":
// not used
case "Lending information":
case "Aanvraaginfo":
// not used
break;
case "Manufacturer":
case "Vervaardiger":
// not used
break;
default:
// ignore
break;
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>De</psi:text>
* <psi:text href="CLK?IKT=4&TRM=Foundation">Foundation</psi:text>
* <psi:text>/ Isaac Asimov ; [vert. uit het Engels door Jack Kröner]</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=422449059&REC=*">
* De buitengewone reis / Silvio Camboni
* </psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processTitle(@NonNull final Iterable<String> currentData) {
final String[] cleanedData = String.join(" ", currentData).split("/");
book.putString(DBKey.TITLE, cleanedData[0].strip());
// It's temping to decode [1], as this is the author as it appears on the cover,
// but the data has proven to be very unstructured and mostly unusable.
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068561504">Isaak Judovič Ozimov (1920-1992)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068870728">Jean-Pol is Jean-Paul Van den Broeck</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=070047596">Dirk Stallaert (1955-)</psi:text>
* <psi:text>;</psi:text>
* <psi:text href="REL?PPN=073286796">Leo Loedts</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="REL?PPN=068852002">Ruurd Feenstra (1904-1974)
* (ISNI 0000 0000 2173 3650) </psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
*
*
* <p>
* Note that the author name in the above example can be the "actual" name, and not
* the publicly known/used name, i.e. in this case "Isaac Asimov"
* The 2nd sample shows how the site is creative (hum) about authors using pen-names.
* The 3rd example has a list of authors for the same author type.
* The 4th sample shows that dates and other info can be added
* <p>
* Getting author names:
* http://opc4.kb.nl/DB=1/SET=1/TTL=1/REL?PPN=068561504
*
* @param currentData content of {@code labelledData}
* @param type the author type
*/
private void processAuthor(@NonNull final Iterable<String> currentData,
@Author.Type final int type) {
for (final String text : currentData) {
// remove any "(..)" parts in the name
final String cleanedString = text.split("\\(")[0].strip();
// reject separators as for example: <psi:text>;</psi:text>
if (cleanedString.length() == 1) {
return;
}
searchEngine.processAuthor(Author.from(cleanedString), type, book);
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=841288933&REC=*">Foundation-trilogie</psi:text>
* <psi:text>;</psi:text>
* <psi:text href="CLK?IKT=12&TRM=841288933&REC=*">dl. 1</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=12&TRM=851863523&REC=*">Discus-serie</psi:text>
* <psi:text>; </psi:text>
* <psi:text href="CLK?IKT=12&TRM=821611178&REC=*">Kluitman jeugdserie</psi:text>
* <psi:text> ; </psi:text>
* <psi:text href="CLK?IKT=12&TRM=821611178&REC=*">J 1247</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processSeries(@NonNull final List<String> currentData) {
book.add(Series.from(currentData.get(0)));
// the number part is totally unstructured
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>Deel 1 / blah</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processSeriesNumber(@NonNull final List<String> currentData) {
// This element is listed BEFORE the Series ("reeks") itself so store it tmp.
// Note it's often missing altogether
final String[] nrStr = currentData.get(0).split("/")[0].split(" ");
if (nrStr.length > 1) {
tmpSeriesNr = nrStr[1];
} else {
tmpSeriesNr = nrStr[0];
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text mark="highlight">90-229-5335-1</psi:text>
* <psi:text>(geb.)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text mark="highlight">978-94-6373145-4</psi:text>
* <psi:text> (paperback)</psi:text>
* </psi:line>
* <psi:line>
* <psi:text> </psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text> (Geb.; f. 4,50)</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>2-256-90374-5 : 40.00F</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text> : 42.00F</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processIsbn(@NonNull final List<String> currentData) {
for (final String text : currentData) {
if (Character.isDigit(text.charAt(0))) {
if (!book.contains(DBKey.BOOK_ISBN)) {
final String digits = SearchEngineUtils.isbn(text.split(":")[0]);
// Do a crude test on the length and hope for the best
// (don't do a full ISBN test here, no need)
if (digits != null && (digits.length() == 10 || digits.length() == 13)) {
book.putString(DBKey.BOOK_ISBN, digits);
}
}
} else if (text.charAt(0) == '(') {
if (!book.contains(DBKey.FORMAT)) {
// Skip the 1th bracket, and split either on closing or on semicolon
final String value = ISBN_BOUNDARY_PATTERN.split(text.substring(1))[0].strip();
if (!value.isBlank()) {
book.putString(DBKey.FORMAT, value);
}
}
}
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=3003&TRM=Breda">Breda</psi:text>
* <psi:text> : </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Dark">Dark</psi:text>
* <psi:text> </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Dragon">Dragon</psi:text>
* <psi:text> </psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Books">Books</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text href="CLK?IKT=3003&TRM=Utrecht">Utrecht</psi:text>
* <psi:text>[</psi:text>
* <psi:text href="CLK?IKT=3003&TRM=etc.">etc.</psi:text>
* <psi:text>] :</psi:text>
* <psi:text href="CLK?IKT=3003&TRM=Bruna">Bruna</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processPublisher(@NonNull final List<String> currentData) {
String publisherName = currentData.stream()
.filter(name -> !name.isEmpty())
.collect(Collectors.joining(" "));
// the part before the ":" is (usually?) the city. 2nd part is the publisher
if (publisherName.contains(":")) {
publisherName = publisherName.split(":")[1].strip();
}
book.add(Publisher.from(publisherName));
}
/**
* Process a year field. Once again the data is not structured, but at least
* it's guessable. Some examples:
*
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>1983</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>[2019]</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>cop. 1986</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>c1977, cover 1978</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processDatePublished(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.BOOK_PUBLICATION__DATE)) {
// Grab the first bit before a comma, and strip it for digits + hope for the best
final String year = SearchEngineUtils.digits(currentData.get(0).split(",")[0]);
if (!year.isEmpty()) {
try {
book.setPublicationDate(Integer.parseInt(year));
} catch (@NonNull final NumberFormatException ignore) {
// ignore
}
}
}
}
/**
* Process the number-of-pages field. Once again the data is not structured, but at least
* it's guessable. Some examples:
*
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>48 pagina's</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>156 p</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processPages(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.PAGE_COUNT)) {
try {
final String cleanedString = currentData.get(0).split(" ")[0];
final int pages = Integer.parseInt(cleanedString);
book.putString(DBKey.PAGE_COUNT, String.valueOf(pages));
} catch (@NonNull final NumberFormatException e) {
// use source
book.putString(DBKey.PAGE_COUNT, currentData.get(0));
}
}
}
/**
* <pre>{@code
* <psi:labelledData>
* <psi:line>
* <psi:text>gekleurde illustraties</psi:text>
* </psi:line>
* </psi:labelledData>
*
* <psi:labelledData>
* <psi:line>
* <psi:text>zw. ill</psi:text>
* </psi:line>
* </psi:labelledData>
* }</pre>
*
* @param currentData content of {@code labelledData}
*/
private void processIllustration(@NonNull final List<String> currentData) {
if (!book.contains(DBKey.COLOR)) {
book.putString(DBKey.COLOR, currentData.get(0));
}
}
private void processDescription(final List<String> currentData) {
book.putString(DBKey.DESCRIPTION, currentData
.stream()
.filter(name -> !name.isEmpty())
.collect(Collectors.joining(" ")));
}
}
|
43982_0 | package com.techgrounds.netflix.model;
import lombok.*;
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class MockupMovie {
private String id;
private String original_title;
private String overview;
private String poster_path;
// hierin staat welke json data de TMDB endpoint terug moet geven, zonder dat de data zelf mooier gemaakt is
} | tg-netflix/backend | src/main/java/com/techgrounds/netflix/model/MockupMovie.java | 112 | // hierin staat welke json data de TMDB endpoint terug moet geven, zonder dat de data zelf mooier gemaakt is | line_comment | nl | package com.techgrounds.netflix.model;
import lombok.*;
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class MockupMovie {
private String id;
private String original_title;
private String overview;
private String poster_path;
// hierin staat<SUF>
} |
140380_11 | package com.page.objects;
import org.openqa.selenium.By;
public class ObjDashBoard {
public static By caseIdFilter=By.xpath("//div//div[.='Dossier-ID']/../..//*[@id='pui_filter']");
public static By rebutTrigFilter=By.xpath("//div//div[.='Rebuttable Trigger']");
public static By filterOverlay=By.cssSelector("#_popOversContainer>#po0");
public static By searchText=By.cssSelector("input[name$='SearchText']");
public static By btnApply=By.xpath("//button[.='Toepassen']");
public static By dashboardTable=By.cssSelector(".gridTable[pl_prop_class='Assign-WorkBasket']>tbody>tr.oddRow");
public static By noItems=By.xpath("//tr[@id='Grid_NoResults']//div[contains(.,'Geen items')]");
public static By casePat=By.xpath("//tr[@id='PReportPage$ppxResults$l3']");
public static By secDate=By.xpath("//td[@data-attribute-name='Geplande datum']");
public static By primDate=By.xpath("//div/span[@data-test-id='201507210538070209958']");
public static String newTab="//li[@role='tab' and contains(@title,'<signalcase>')]";
//status
public static By caseStatus=By.xpath("//div/span[.='Status']/../..//span[@class='standard_small']");
public static By rebTrig=By.xpath("//div/span[.='Rebuttable Trigger']/../..//span[@class='standard_small']");
//public static By samDsierCrtion=By.xpath("//div/span[.='Status']/../..//span[.='Open-SamDossierCreation']");
//public static By resolvedNotRebutted=By.xpath("//div/span[.='Status']/../..//span[.='Resolved-NotRebutted']");
//PCP cases
public static By gadgetFrame=By.cssSelector("#PegaGadget0Ifr,#PegaGadget1Ifr,#PegaGadget2Ifr");
public static String groupItems="//h3[.='<groupItem>' and @class='layout-group-item-title']";
public static By btnVerzenden=By.cssSelector("a.RaboOrange");
public static By closeTabs=By.cssSelector("span#close");
public static By actieButton=By.xpath("//a[@data-test-id='20170927100430055317911']");
public static By verzendBtn=By.xpath("//button[@id='ModalButtonSubmit']");
public static By newDosBtn=By.linkText("Nieuw Dossier");
public static By teamBtn=By.cssSelector("span[tabtitle='TeamBoard']>span");
public static By newCaseBtn=By.xpath("//span[@tabtitle='New Cases']//*[@inanchor]");
public static By newCaseBtnSub=By.cssSelector("button[data-click*='CreateManualRebuttableSignalCase']");
public static By wissenBtn=By.xpath("//button[.='Wissen']");
public static By searchBtn=By.xpath("//button[.='Zoeken']");
public static By achterNaam=By.cssSelector("input[name$='Achternaam']");
public static By signalType=By.xpath("//select[@name='$PpyDisplayHarness$pSignalType']");
public static By dateSignal=By.xpath("//input[@name='$PSearchNewCases$pOtherSignEventDate']");
public static By loanNumber=By.cssSelector("input[name$='Agreementnumber']");
public static By postalCode=By.cssSelector("input[name$='Postcode']");
public static By houseNumber=By.cssSelector("input[name$='Huisnummer']");
public static By birthDay=By.cssSelector("input[name$='Geboortedatum']");
//information message
//public static By inforMsg=By.cssSelector("informationmessage_dataLabelRead");
public static By inforMsg=By.xpath("//*[contains(@class,'informationmessage_dataLabelRead')]");
public static By errorMsg=By.xpath("//div[.='Geen resultaten gevonden']");
public static By submMsg=By.xpath("//div[.='De case is aangemaakt']");
public static By refreshIcon=By.linkText("Vernieuwen");
public static By stopBtn=By.linkText("Stoppen");
public static By samManagedTrue=By.cssSelector("label[for='IsSAMManagedtrue']");
public static By samManagedFalse=By.cssSelector("label[for='IsSAMManagedfalse']");
public static By assessMentReason=By.cssSelector("div[data-ui-meta*='ResultReasonDesc']>div>span");
public static By assessMentReasonCons=By.xpath("//span[@data-test-id='20171025124007076522655']");
public static By hypotheekBedrag=By.xpath("//label[contains(.,'Ja')]");
public static By hypotheekBedragCons=By.cssSelector("label[for='pyWorkPageQuestionnaireMainQuestionList1AnswerOVERIGBNPQ1A2']");
public static By eventDate=By.cssSelector("div[data-ui-meta*='OtherSignEventDate']>span");
//1st 4 mandatory buttons
public static By mandatory1=By.xpath("//div//span[contains(.,'Wordt een betaalachterstand van 100 euro of meer')]/../../../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory2=By.xpath("//div//span[contains(.,'Heeft de faciliteit een betaalachterstand die')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory3=By.xpath("//div//span[contains(.,'ruimte voor de komende 3 maanden onvoldoende')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory4=By.xpath("//div//span[contains(.,'Wordt een onderhandse of gedwongen openbare verkoop')]/../../../following-sibling::div//label[contains(.,'Ja')]");
//dpd30 properties
public static By mandatory5=By.xpath("//span[contains(.,'Is betaalprobleem structureel')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory6=By.xpath("//span[contains(.,'Duurt oplossen betaalprobleem langer dan 90 dagen')]/../following-sibling::div//label[contains(.,'Ja')]");
//rebute
public static By refute=By.cssSelector("label[for$='Rebutted']");
public static By Notrefute=By.cssSelector("label[for$='NotRebutted']");
public static By doNotJudge=By.cssSelector("label[for$='NotAssessed']");
public static By slctRsonCode=By.cssSelector("select[name$='ResultReasonCode']");
public static By slctTeam=By.xpath("//select[@name='$PpyDisplayHarness$ppySearchText']");
public static By enterReason=By.xpath("//*[@name='$PpyWorkPage$pComments']");
//beslag options
public static By executoriaal=By.cssSelector("label[for$='EXECCLAIM']");
public static By conservatoir=By.cssSelector("label[for$='CONCLAIM']");
public static By verkeerdSignaal=By.cssSelector("label[for$='WRONGSIGNALCLAIM']");
public static By selectDossier=By.cssSelector("input~[name$='pySelected']");
public static By claimAmount=By.cssSelector("input[name$='ClaimAmount']");
public static By productEn=By.xpath("//h3[contains(.,'Producten')]");
public static By lstLoanNo=By.xpath("//td[@data-attribute-name='Leningdeel']");
public static By collateralTab=By.xpath("//h3[contains(.,'Onderpand')]");
public static By collObjTypeDesc=By.xpath("//td[@data-attribute-name='Soort registergoed']");
public static By bkrTab=By.xpath("//h3[contains(.,'BKR')]");
public static By bkrContRel=By.xpath("//div[@node_name='BKRContractRelation']");
public static By overlijdenContRel=By.xpath("//div[@class='content-item content-label item-1 flex flex-row informationmessage_dataLabelRead dataLabelRead informationmessage_dataLabelRead']");
}
| thananauto/java-test-frameworks | cucumber-picocontainer/src/test/java/com/page/objects/ObjDashBoard.java | 2,392 | //div//span[contains(.,'Wordt een onderhandse of gedwongen openbare verkoop')]/../../../following-sibling::div//label[contains(.,'Ja')]"); | line_comment | nl | package com.page.objects;
import org.openqa.selenium.By;
public class ObjDashBoard {
public static By caseIdFilter=By.xpath("//div//div[.='Dossier-ID']/../..//*[@id='pui_filter']");
public static By rebutTrigFilter=By.xpath("//div//div[.='Rebuttable Trigger']");
public static By filterOverlay=By.cssSelector("#_popOversContainer>#po0");
public static By searchText=By.cssSelector("input[name$='SearchText']");
public static By btnApply=By.xpath("//button[.='Toepassen']");
public static By dashboardTable=By.cssSelector(".gridTable[pl_prop_class='Assign-WorkBasket']>tbody>tr.oddRow");
public static By noItems=By.xpath("//tr[@id='Grid_NoResults']//div[contains(.,'Geen items')]");
public static By casePat=By.xpath("//tr[@id='PReportPage$ppxResults$l3']");
public static By secDate=By.xpath("//td[@data-attribute-name='Geplande datum']");
public static By primDate=By.xpath("//div/span[@data-test-id='201507210538070209958']");
public static String newTab="//li[@role='tab' and contains(@title,'<signalcase>')]";
//status
public static By caseStatus=By.xpath("//div/span[.='Status']/../..//span[@class='standard_small']");
public static By rebTrig=By.xpath("//div/span[.='Rebuttable Trigger']/../..//span[@class='standard_small']");
//public static By samDsierCrtion=By.xpath("//div/span[.='Status']/../..//span[.='Open-SamDossierCreation']");
//public static By resolvedNotRebutted=By.xpath("//div/span[.='Status']/../..//span[.='Resolved-NotRebutted']");
//PCP cases
public static By gadgetFrame=By.cssSelector("#PegaGadget0Ifr,#PegaGadget1Ifr,#PegaGadget2Ifr");
public static String groupItems="//h3[.='<groupItem>' and @class='layout-group-item-title']";
public static By btnVerzenden=By.cssSelector("a.RaboOrange");
public static By closeTabs=By.cssSelector("span#close");
public static By actieButton=By.xpath("//a[@data-test-id='20170927100430055317911']");
public static By verzendBtn=By.xpath("//button[@id='ModalButtonSubmit']");
public static By newDosBtn=By.linkText("Nieuw Dossier");
public static By teamBtn=By.cssSelector("span[tabtitle='TeamBoard']>span");
public static By newCaseBtn=By.xpath("//span[@tabtitle='New Cases']//*[@inanchor]");
public static By newCaseBtnSub=By.cssSelector("button[data-click*='CreateManualRebuttableSignalCase']");
public static By wissenBtn=By.xpath("//button[.='Wissen']");
public static By searchBtn=By.xpath("//button[.='Zoeken']");
public static By achterNaam=By.cssSelector("input[name$='Achternaam']");
public static By signalType=By.xpath("//select[@name='$PpyDisplayHarness$pSignalType']");
public static By dateSignal=By.xpath("//input[@name='$PSearchNewCases$pOtherSignEventDate']");
public static By loanNumber=By.cssSelector("input[name$='Agreementnumber']");
public static By postalCode=By.cssSelector("input[name$='Postcode']");
public static By houseNumber=By.cssSelector("input[name$='Huisnummer']");
public static By birthDay=By.cssSelector("input[name$='Geboortedatum']");
//information message
//public static By inforMsg=By.cssSelector("informationmessage_dataLabelRead");
public static By inforMsg=By.xpath("//*[contains(@class,'informationmessage_dataLabelRead')]");
public static By errorMsg=By.xpath("//div[.='Geen resultaten gevonden']");
public static By submMsg=By.xpath("//div[.='De case is aangemaakt']");
public static By refreshIcon=By.linkText("Vernieuwen");
public static By stopBtn=By.linkText("Stoppen");
public static By samManagedTrue=By.cssSelector("label[for='IsSAMManagedtrue']");
public static By samManagedFalse=By.cssSelector("label[for='IsSAMManagedfalse']");
public static By assessMentReason=By.cssSelector("div[data-ui-meta*='ResultReasonDesc']>div>span");
public static By assessMentReasonCons=By.xpath("//span[@data-test-id='20171025124007076522655']");
public static By hypotheekBedrag=By.xpath("//label[contains(.,'Ja')]");
public static By hypotheekBedragCons=By.cssSelector("label[for='pyWorkPageQuestionnaireMainQuestionList1AnswerOVERIGBNPQ1A2']");
public static By eventDate=By.cssSelector("div[data-ui-meta*='OtherSignEventDate']>span");
//1st 4 mandatory buttons
public static By mandatory1=By.xpath("//div//span[contains(.,'Wordt een betaalachterstand van 100 euro of meer')]/../../../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory2=By.xpath("//div//span[contains(.,'Heeft de faciliteit een betaalachterstand die')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory3=By.xpath("//div//span[contains(.,'ruimte voor de komende 3 maanden onvoldoende')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory4=By.xpath("//div//span[contains(.,'Wordt een<SUF>
//dpd30 properties
public static By mandatory5=By.xpath("//span[contains(.,'Is betaalprobleem structureel')]/../following-sibling::div//label[contains(.,'Ja')]");
public static By mandatory6=By.xpath("//span[contains(.,'Duurt oplossen betaalprobleem langer dan 90 dagen')]/../following-sibling::div//label[contains(.,'Ja')]");
//rebute
public static By refute=By.cssSelector("label[for$='Rebutted']");
public static By Notrefute=By.cssSelector("label[for$='NotRebutted']");
public static By doNotJudge=By.cssSelector("label[for$='NotAssessed']");
public static By slctRsonCode=By.cssSelector("select[name$='ResultReasonCode']");
public static By slctTeam=By.xpath("//select[@name='$PpyDisplayHarness$ppySearchText']");
public static By enterReason=By.xpath("//*[@name='$PpyWorkPage$pComments']");
//beslag options
public static By executoriaal=By.cssSelector("label[for$='EXECCLAIM']");
public static By conservatoir=By.cssSelector("label[for$='CONCLAIM']");
public static By verkeerdSignaal=By.cssSelector("label[for$='WRONGSIGNALCLAIM']");
public static By selectDossier=By.cssSelector("input~[name$='pySelected']");
public static By claimAmount=By.cssSelector("input[name$='ClaimAmount']");
public static By productEn=By.xpath("//h3[contains(.,'Producten')]");
public static By lstLoanNo=By.xpath("//td[@data-attribute-name='Leningdeel']");
public static By collateralTab=By.xpath("//h3[contains(.,'Onderpand')]");
public static By collObjTypeDesc=By.xpath("//td[@data-attribute-name='Soort registergoed']");
public static By bkrTab=By.xpath("//h3[contains(.,'BKR')]");
public static By bkrContRel=By.xpath("//div[@node_name='BKRContractRelation']");
public static By overlijdenContRel=By.xpath("//div[@class='content-item content-label item-1 flex flex-row informationmessage_dataLabelRead dataLabelRead informationmessage_dataLabelRead']");
}
|
65010_98 | ////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//
// taprats -- an interactive design tool for computer-generated
// Islamic patterns.
//
// Copyright 2000 Craig S. Kaplan.
// email: csk at cs.washington.edu
//
// Copyright 2010 Pierre Baillargeon
// email: pierrebai at hotmail.com
//
// This file is part of Taprats.
//
// Taprats is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Taprats 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 for more details.
//
// You should have received a copy of the GNU General Public License
// along with Taprats. If not, see <http://www.gnu.org/licenses/>.
/*
* Map.java
*
* The implementation of a planar map abstraction. A planar map is
* an (undirected) graph represented on the plane in such a way that
* edges don't cross vertices or other edges.
*
* This is one of the big daddy structures of computational geometry.
* The right way to do it is with a doubly-connected edge list structure,
* complete with half edges and a face abstraction. Because I'm lazy
* and because of the sheer coding involved, I'm doing something simpler,
* more like an ordinary graph. The disadvantage is that I don't maintain
* faces explicitly, which can make face colouring for islamic patterns
* tricky later. But it's more tractable than computing overlays of
* DCELs.
*/
package csk.taprats.geometry;
import java.util.Vector;
import java.util.Enumeration;
import csk.taprats.general.Loose;
import csk.taprats.general.Sort;
import csk.taprats.general.Comparison;
public class Map
implements Cloneable
{
private Vector vertices;
private Vector edges;
private int index;
public Map()
{
this.vertices = new Vector();
this.edges = new Vector();
this.index=0;
}
/*
* Some obvious getters.
*/
public int numVertices()
{
return vertices.size();
}
public Enumeration getVertices()
{
return vertices.elements();
}
public int numEdges()
{
return edges.size();
}
public Enumeration getEdges()
{
return edges.elements();
}
/*
* Remove stuff from the map.
*/
public void removeEdge( Edge e )
{
e.getV1().removeEdge( e );
e.getV2().removeEdge( e );
edges.removeElement( e );
}
public void removeVertex( Vertex v )
{
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
edge.getOther( v ).removeEdge( edge );
edges.removeElement( edge );
}
vertices.removeElement( v );
}
public Object clone()
{
Map ret = new Map();
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
Vertex nv = new Vertex( ret, vert.getPosition() );
vert.copy = nv;
ret.vertices.addElement( nv );
}
for( Enumeration e = edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Edge ne = new Edge( ret, edge.getV1().copy, edge.getV2().copy );
ret.edges.addElement( ne );
// FIXME -- this could be a bit faster. Really we could
// copy the order of the edges leaving a vertex wholesale.
// I don't think it'll make that big a difference. The
// max expected degree of the vertices in the maps we'll be
// dealing with is 6.
ne.getV1().insertEdge( ne );
ne.getV2().insertEdge( ne );
}
return ret;
}
/*
* Routines used for spatial sorting of edges and vertices.
*/
private static int lexCompareEdges( double a, double b )
{
double d = a - b;
if( Loose.zero( d ) ) {
return 0;
} else if( d < 0.0 ) {
return -1;
} else {
return 1;
}
}
private static int lexComparePoints( Point a, Point b )
{
double dx = a.getX() - b.getX();
if( Loose.zero( dx ) ) {
double dy = a.getY() - b.getY();
if( Loose.zero( dy ) ) {
return 0;
} else if( dy < 0.0 ) {
return -1;
} else {
return 1;
}
} else if( dx < 0.0 ) {
return -1;
} else {
return 1;
}
}
private void sortVertices()
{
Sort.quickSort( vertices, 0, vertices.size() - 1,
new Comparison() {
public int compare( Object a, Object b )
{
Vertex v1 = (Vertex)a;
Vertex v2 = (Vertex)b;
return lexComparePoints(
v1.getPosition(), v2.getPosition() );
}
} );
}
private void sortEdges()
{
Sort.quickSort( edges, 0, edges.size() - 1,
new Comparison() {
public int compare( Object a, Object b )
{
Edge e1 = (Edge)a;
Edge e2 = (Edge)b;
return lexCompareEdges( e1.getMinX(), e2.getMinX() );
}
} );
}
/*
* Get a Map Vertex given that we're asserting the vertex
* doesn't lie on an edge in the map.
*/
final Vertex getVertex_Simple( Point pt )
{
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex v = (Vertex)( vertices.elementAt( idx ) );
Point cur = v.getPosition();
int cmp = lexComparePoints( pt, cur );
if( cmp == 0 ) {
return v;
} else if( cmp < 0 ) {
Vertex vert = new Vertex( this, pt );
vertices.insertElementAt( vert, idx );
return vert;
}
}
Vertex vert = new Vertex( this, pt );
vertices.addElement( vert );
return vert;
}
/*
* Insert an edge given that we know the edge doesn't interact
* with other edges or vertices other than its endpoints.
*/
final void insertEdge_Simple( Edge edge )
{
double xm = edge.getMinX();
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
double xmcur = e.getMinX();
if( lexCompareEdges( xm, xmcur ) < 0 ) {
edges.insertElementAt( edge, idx );
return;
}
}
edges.addElement( edge );
}
/*
* Insert the edge connecting two vertices, including updating
* the neighbour lists for the vertices.
*/
public final Edge insertEdge( Vertex v1, Vertex v2 )
{
/*
* I don't want this in here because I don't like silently fixing
* mistakes. If someone tries to insert a trivial edge, I want
* to solve the problem, not hide the symptom.
if( v1.equals( v2 ) ) {
System.err.println( "Warning - trivial edge not inserted." );
return null;
}
*/
Edge e = new Edge( this, v1, v2 );
insertEdge_Simple( e );
v1.insertEdge( e );
v2.insertEdge( e );
return e;
}
/*
* Split any edge (there is at most one) that intersects
* this new vertex. You'll want to make sure this vertex isn't
* a duplicate of one already in the map. That would just
* make life unpleasant.
*/
final void splitEdgesByVertex( Vertex vert )
{
Point vp = vert.getPosition();
double x = vp.getX();
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
double xm = e.getMinX();
if( lexCompareEdges( xm, x ) > 0 ) {
/*
* The edges are sorted by xmin, and this xmin exceeds
* the x value of the vertex. No more interactions.
*/
return;
}
Vertex v1 = e.getV1();
Vertex v2 = e.getV2();
if( Loose.zero(
vp.distToLine( v1.getPosition(), v2.getPosition() ) ) ) {
if( Loose.zero( vp.dist( v1.getPosition() ) ) ||
Loose.zero( vp.dist( v2.getPosition() ) ) ) {
// Don't split if too near endpoints.
continue;
}
// Create the new edge instance.
Edge nedge = new Edge( this, vert, v2 );
// We don't need to fix up v1 -- it can still point
// to the same edge.
// Fix up v2.
v2.swapEdge( v1, nedge );
// Fix up the edge object -- it now points to the
// intervening edge.
e.v2 = vert;
// Insert the new edge.
edges.removeElementAt( idx );
insertEdge_Simple( nedge );
insertEdge_Simple( e );
// Update the adjacencies for the splitting vertex
vert.insertEdge( e );
vert.insertEdge( nedge );
// That's it.
return;
}
}
}
/*
* The "correct" version of inserting a vertex. Make sure the
* map stays consistent.
*/
final Vertex getVertex_Complex( Point pt )
{
Vertex vert = getVertex_Simple( pt );
splitEdgesByVertex( vert );
return vert;
}
/*
* The publically-accessible version.
*/
public final Vertex insertVertex( Point pt )
{
return getVertex_Complex( pt );
}
/*
* Applying a motion made up only of uniform scales and translations,
* Angles don't change. So we can just transform each vertex.
*/
void applyTrivialRigidMotion( Transform T )
{
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
vert.pos = T.apply( vert.getPosition() );
}
}
public void scale( double s )
{
applyTrivialRigidMotion( Transform.scale( s ) );
}
public void translate( double x, double y )
{
applyTrivialRigidMotion( Transform.translate( x, y ) );
}
/*
* In the general case, the vertices and edges must be re-sorted.
*/
void applyGeneralRigidMotion( Transform T )
{
// Transform all the vertices.
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
vert.applyRigidMotion( T );
}
// Now sort everything.
sortVertices();
sortEdges();
}
public void transformMap( Transform T )
{
applyGeneralRigidMotion( T );
}
/*
* Transform a single vertex.
*/
public void transformVertex( Vertex v, Transform T )
{
// This isn't entirely trivial:
// 1. Transform the vertex itself and recalculate the neighbour
// angles.
// 2. For each vertex adjacent to this one, reinsert the connecting
// edge into the other vertex's neighbour list.
// 3. Reinsert the vertex into the map's vertex list -- its
// x position may have changed.
// 4. Re-sort the edge list, since edges which began at the
// transformed vertex may shift in the edge list.
//
// Right now most of this, especially steps 3 and 4, are done
// in the obvious, slow way. With more careful programming, we
// could break the process down further and do some parts faster,
// like searching for the vertex's new position relative to its
// current position. At this point, however, that's not a huge
// win.
// Transform the position of the vertex.
v.applyRigidMotion( T );
// Reorganize the vertices adjacent to this vertex.
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex other = edge.getOther( v );
other.removeEdge( edge );
other.insertEdge( edge );
}
// This vertex's x position may have changed. Reposition
// it in the array of vertices.
vertices.removeElement( v );
Point pt = v.getPosition();
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex vo = (Vertex)( vertices.elementAt( idx ) );
Point cur = vo.getPosition();
int cmp = lexComparePoints( pt, cur );
if( cmp < 0 ) {
vertices.insertElementAt( v, idx );
return;
}
}
vertices.addElement( v );
// Sigh -- I guess resort the edges.
sortEdges();
}
/*
* Given another vector of vertices, add them to the vertices of the
* current map. We can do this in linear time with a simple merge
* algorithm. Note that we want to coalesce identical vertices to
* eliminate duplicates.
*/
private void mergeVertices( Vector your_verts )
{
Vector my_verts = vertices;
int my_size = my_verts.size();
int your_size = your_verts.size();
vertices = new Vector( my_size + your_size );
int my_i = 0;
int your_i = 0;
while( true ) {
if( my_i == my_size ) {
if( your_i == your_size ) {
// done!
return;
} else {
Vertex your_v = (Vertex)( your_verts.elementAt( your_i ) );
Vertex nv = new Vertex( this, your_v.getPosition() );
vertices.addElement( nv );
your_v.copy = nv;
++your_i;
}
} else {
if( your_i == your_size ) {
vertices.addElement( my_verts.elementAt( my_i ) );
++my_i;
} else {
// Darn -- have to actually merge.
Vertex my_v = (Vertex)( my_verts.elementAt( my_i ) );
Vertex your_v = (Vertex)( your_verts.elementAt( your_i ) );
int cmp = lexComparePoints(
my_v.getPosition(), your_v.getPosition() );
if( cmp < 0 ) {
// my_v goes first.
vertices.addElement( my_v );
++my_i;
} else if( cmp == 0 ) {
// It's a toss up.
vertices.addElement( my_v );
your_v.copy = my_v;
++my_i;
++your_i;
} else if( cmp > 0 ) {
// your_v goes first.
Vertex nv = new Vertex( this, your_v.getPosition() );
vertices.addElement( nv );
your_v.copy = nv;
++your_i;
}
}
}
}
}
/*
* Merge two maps. The bread and butter of the Map class. This is a
* complicated computational geometry algorithm with a long and
* glorious tradition :^)
*
* The goal is to form a map from the union of the two sets of
* vertices (eliminating duplicates) and the union of the two sets
* of edges (splitting edges whenever intersections occur).
*
* There are very efficient ways to do this, reporting edge-edge
* intersections using a plane-sweep algorithm. Implementing
* this merge code in all its glory would be too much work. Since
* I have to use all my own code, I'm going to resort to a simplified
* (and slower) version of the algorithm.
*/
public void mergeMap( Map other, boolean consume )
{
/*
* Sanity checks to use when debugging.
boolean at_start = verify();
if( !at_start ) {
System.err.println( "Bad at start." );
}
if( !other.verify() ) {
System.err.println( "Other bad at start." );
}
*/
// Here's how I'm going to do this.
//
// 1. Check all intersections between edges from this map
// and from the other map. Record the positions of the
// intersections.
//
// 2. For each intersection position, get the vertex in both
// maps, forcing edges to split where the intersections will
// occur.
//
// 3. Merge the vertices.
//
// 4. Add the edges in the trivial way, since now there will
// be no intersections.
//
// Yech -- pretty slow. But I shudder at the thought of
// doing it with maximal efficiency.
//
// In practice, this routine has proven to be efficient enough
// for the Islamic design tool. Phew!
// Step 0 -- setup.
// Create a vector to hold the intersections.
if( !consume ) {
// Copy the other map so we don't destroy it.
other = (Map)( other.clone() );
}
Vector intersections = new Vector();
// Step 1
for( Enumeration e = other.getEdges(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
// To check all intersections of this edge with edges in
// the current map, we can use the optimization that
// edges are stored in sorted order by min x. So at the
// very least, skip the suffix of edges whose minimum x values
// are past the max x of the edge to check.
Point ep = edge.getV1().getPosition();
Point eq = edge.getV2().getPosition();
double exm = Math.max( ep.getX(), eq.getX() );
for( Enumeration me = getEdges(); me.hasMoreElements(); ) {
Edge cur = (Edge)( me.nextElement() );
Point cp = cur.getV1().getPosition();
Point cq = cur.getV2().getPosition();
if( lexCompareEdges( cur.getMinX(), exm ) > 0 ) {
break;
}
Point ipt = Intersect.getTrueIntersection( ep, eq, cp, cq );
if( ipt != null ) {
intersections.addElement( ipt );
}
}
}
// Step 2
for( Enumeration e = intersections.elements(); e.hasMoreElements(); ) {
Point p = (Point)( e.nextElement() );
getVertex_Complex( p );
other.getVertex_Complex( p );
}
// Step 3
mergeVertices( other.vertices );
// Step 4
for( Enumeration e = other.edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
Edge ne = new Edge( this, v1, v2 );
// Rather than using insertEdge_Simple, we tack all new edges
// to the end of the edge list...
edges.addElement( ne );
v1.insertEdge( ne );
v2.insertEdge( ne );
}
// ... and then sort everything together for speed.
sortEdges();
// I guess that's it!
/*
if( at_start && !verify() ) {
System.err.println( "it went bad." );
dump( System.err );
}
*/
}
public void mergeMap( Map other )
{
mergeMap( other, false );
}
/*
* A simpler merge routine that assumes that the two maps
* don't interact except at vertices, so edges don't need to
* be checked for intersections.
*/
public void mergeSimple( Map other )
{
// System.err.println( "mergeSimple begin" );
mergeVertices( other.vertices );
for( Enumeration e = other.getEdges(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
// insertEdge( edge.getV1().copy, edge.getV2().copy );
Edge nedge = new Edge( this, v1, v2 );
v1.insertEdge( nedge );
v2.insertEdge( nedge );
edges.addElement( nedge );
}
sortEdges();
}
/*
* It's often the case that we want to merge a transformed copy of
* a map into another map, or even a collection of transformed copies.
* Since transforming a map requires a slow cloning, we can save lots
* of time and memory by transforming and merging simultaneously.
* Here, we transform vertices as they are put into the current map.
*/
public void mergeSimpleMany( Map other, Vector transforms )
{
for( Enumeration e = transforms.elements(); e.hasMoreElements(); ) {
Transform T = (Transform)( e.nextElement() );
for( Enumeration v = other.getVertices(); v.hasMoreElements(); ) {
Vertex vert = (Vertex)( v.nextElement() );
vert.copy = getVertex_Simple( T.apply( vert.getPosition() ) );
}
for( Enumeration v = other.getEdges(); v.hasMoreElements(); ) {
Edge edge = (Edge)( v.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
Edge nedge = new Edge( this, v1, v2 );
v1.insertEdge( nedge );
v2.insertEdge( nedge );
edges.addElement( nedge );
}
}
sortEdges();
}
public Edge getLine()
{
index=(int) (Math.random()*edges.size());
Edge edge = (Edge)( edges.elementAt( index ) );
return edge;
}
/*
* Print a text version of the map.
*/
public void dump( java.io.PrintStream ow )
{
ow.println( "" + vertices.size() + " vertices." );
ow.println( "" + edges.size() + " edges.\n" );
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex v = (Vertex)( vertices.elementAt( idx ) );
ow.println( "vertex " + idx + " at " + v.getPosition() );
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
ow.println( "\t--> " + edges.indexOf( edge ) );
}
}
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge edge = (Edge)( edges.elementAt( idx ) );
ow.println( "edge " + idx +
" from " + vertices.indexOf( edge.getV1() ) +
" to " + vertices.indexOf( edge.getV2() ) );
}
}
/*
* A big 'ole sanity check for maps. Throw together a whole collection
* of consistency checks. When debugging maps, call early and call often.
*
* It would probably be better to make this function provide the error
* messages through a return value or exception, but whatever.
*/
public boolean verify()
{
boolean good = true;
// Make sure there are no trivial edges.
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
if( e.getV1().equals( e.getV2() ) ) {
System.err.println( "Trivial edge " + idx );
good = false;
}
}
for( Enumeration e = edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
// Make sure that for every edge, the edge's endpoints
// are know vertices in the map.
if( !vertices.contains( edge.getV1() ) ) {
System.err.println( "edge " +
edges.indexOf( edge ) + " V1 not in vertex list." );
good = false;
}
if( !vertices.contains( edge.getV2() ) ) {
System.err.println( "edge " +
edges.indexOf( edge ) + " V2 not in vertex list." );
good = false;
}
// Make sure that the edge's endpoints know about the
// edge, and that the edge is the only connection between
// the two endpoints.
Edge ed = edge.getV1().getNeighbour( edge.getV2() );
if( ed == null ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not found in vertex v1 neighbours for vertex " +
vertices.indexOf( edge.getV1() ) );
good = false;
}
if( !ed.equals( edge ) ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not matched in vertex v1 neighbours for vertex " +
vertices.indexOf( edge.getV1() ) );
good = false;
}
ed = edge.getV2().getNeighbour( edge.getV1() );
if( ed == null ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not found in vertex v2 neighbours for vertex " +
vertices.indexOf( edge.getV2() ) );
good = false;
}
if( !ed.equals( edge ) ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not matched in vertex v2 neighbours for vertex " +
vertices.indexOf( edge.getV2() ) );
good = false;
}
}
// Make sure the edges are in sorted order.
for( int idx = 1; idx < edges.size(); ++idx ) {
Edge e1 = (Edge)( edges.elementAt( idx - 1 ) );
Edge e2 = (Edge)( edges.elementAt( idx ) );
double e1x = e1.getMinX();
double e2x = e2.getMinX();
if( e1x > (e2x + Loose.TOL) ) {
System.err.println( "Sortedness check failed for edges." );
good = false;
}
}
// Make sure the vertices are in sorted order.
for( int idx = 1; idx < vertices.size(); ++idx ) {
Vertex v1 = (Vertex)( vertices.elementAt( idx - 1 ) );
Vertex v2 = (Vertex)( vertices.elementAt( idx ) );
int cmp = lexComparePoints( v1.getPosition(), v2.getPosition() );
if( cmp == 0 ) {
System.err.println( "Duplicate vertices." );
good = false;
} else if( cmp > 0 ) {
System.err.println( "Sortedness check failed for vertices." );
good = false;
}
}
// Other possible checks:
// - Make sure there's no edge from a vertex to itself.
return good;
}
}
| thargor6/JWildfire | src/csk/taprats/geometry/Map.java | 7,676 | // insertEdge( edge.getV1().copy, edge.getV2().copy ); | line_comment | nl | ////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//
// taprats -- an interactive design tool for computer-generated
// Islamic patterns.
//
// Copyright 2000 Craig S. Kaplan.
// email: csk at cs.washington.edu
//
// Copyright 2010 Pierre Baillargeon
// email: pierrebai at hotmail.com
//
// This file is part of Taprats.
//
// Taprats is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Taprats 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 for more details.
//
// You should have received a copy of the GNU General Public License
// along with Taprats. If not, see <http://www.gnu.org/licenses/>.
/*
* Map.java
*
* The implementation of a planar map abstraction. A planar map is
* an (undirected) graph represented on the plane in such a way that
* edges don't cross vertices or other edges.
*
* This is one of the big daddy structures of computational geometry.
* The right way to do it is with a doubly-connected edge list structure,
* complete with half edges and a face abstraction. Because I'm lazy
* and because of the sheer coding involved, I'm doing something simpler,
* more like an ordinary graph. The disadvantage is that I don't maintain
* faces explicitly, which can make face colouring for islamic patterns
* tricky later. But it's more tractable than computing overlays of
* DCELs.
*/
package csk.taprats.geometry;
import java.util.Vector;
import java.util.Enumeration;
import csk.taprats.general.Loose;
import csk.taprats.general.Sort;
import csk.taprats.general.Comparison;
public class Map
implements Cloneable
{
private Vector vertices;
private Vector edges;
private int index;
public Map()
{
this.vertices = new Vector();
this.edges = new Vector();
this.index=0;
}
/*
* Some obvious getters.
*/
public int numVertices()
{
return vertices.size();
}
public Enumeration getVertices()
{
return vertices.elements();
}
public int numEdges()
{
return edges.size();
}
public Enumeration getEdges()
{
return edges.elements();
}
/*
* Remove stuff from the map.
*/
public void removeEdge( Edge e )
{
e.getV1().removeEdge( e );
e.getV2().removeEdge( e );
edges.removeElement( e );
}
public void removeVertex( Vertex v )
{
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
edge.getOther( v ).removeEdge( edge );
edges.removeElement( edge );
}
vertices.removeElement( v );
}
public Object clone()
{
Map ret = new Map();
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
Vertex nv = new Vertex( ret, vert.getPosition() );
vert.copy = nv;
ret.vertices.addElement( nv );
}
for( Enumeration e = edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Edge ne = new Edge( ret, edge.getV1().copy, edge.getV2().copy );
ret.edges.addElement( ne );
// FIXME -- this could be a bit faster. Really we could
// copy the order of the edges leaving a vertex wholesale.
// I don't think it'll make that big a difference. The
// max expected degree of the vertices in the maps we'll be
// dealing with is 6.
ne.getV1().insertEdge( ne );
ne.getV2().insertEdge( ne );
}
return ret;
}
/*
* Routines used for spatial sorting of edges and vertices.
*/
private static int lexCompareEdges( double a, double b )
{
double d = a - b;
if( Loose.zero( d ) ) {
return 0;
} else if( d < 0.0 ) {
return -1;
} else {
return 1;
}
}
private static int lexComparePoints( Point a, Point b )
{
double dx = a.getX() - b.getX();
if( Loose.zero( dx ) ) {
double dy = a.getY() - b.getY();
if( Loose.zero( dy ) ) {
return 0;
} else if( dy < 0.0 ) {
return -1;
} else {
return 1;
}
} else if( dx < 0.0 ) {
return -1;
} else {
return 1;
}
}
private void sortVertices()
{
Sort.quickSort( vertices, 0, vertices.size() - 1,
new Comparison() {
public int compare( Object a, Object b )
{
Vertex v1 = (Vertex)a;
Vertex v2 = (Vertex)b;
return lexComparePoints(
v1.getPosition(), v2.getPosition() );
}
} );
}
private void sortEdges()
{
Sort.quickSort( edges, 0, edges.size() - 1,
new Comparison() {
public int compare( Object a, Object b )
{
Edge e1 = (Edge)a;
Edge e2 = (Edge)b;
return lexCompareEdges( e1.getMinX(), e2.getMinX() );
}
} );
}
/*
* Get a Map Vertex given that we're asserting the vertex
* doesn't lie on an edge in the map.
*/
final Vertex getVertex_Simple( Point pt )
{
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex v = (Vertex)( vertices.elementAt( idx ) );
Point cur = v.getPosition();
int cmp = lexComparePoints( pt, cur );
if( cmp == 0 ) {
return v;
} else if( cmp < 0 ) {
Vertex vert = new Vertex( this, pt );
vertices.insertElementAt( vert, idx );
return vert;
}
}
Vertex vert = new Vertex( this, pt );
vertices.addElement( vert );
return vert;
}
/*
* Insert an edge given that we know the edge doesn't interact
* with other edges or vertices other than its endpoints.
*/
final void insertEdge_Simple( Edge edge )
{
double xm = edge.getMinX();
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
double xmcur = e.getMinX();
if( lexCompareEdges( xm, xmcur ) < 0 ) {
edges.insertElementAt( edge, idx );
return;
}
}
edges.addElement( edge );
}
/*
* Insert the edge connecting two vertices, including updating
* the neighbour lists for the vertices.
*/
public final Edge insertEdge( Vertex v1, Vertex v2 )
{
/*
* I don't want this in here because I don't like silently fixing
* mistakes. If someone tries to insert a trivial edge, I want
* to solve the problem, not hide the symptom.
if( v1.equals( v2 ) ) {
System.err.println( "Warning - trivial edge not inserted." );
return null;
}
*/
Edge e = new Edge( this, v1, v2 );
insertEdge_Simple( e );
v1.insertEdge( e );
v2.insertEdge( e );
return e;
}
/*
* Split any edge (there is at most one) that intersects
* this new vertex. You'll want to make sure this vertex isn't
* a duplicate of one already in the map. That would just
* make life unpleasant.
*/
final void splitEdgesByVertex( Vertex vert )
{
Point vp = vert.getPosition();
double x = vp.getX();
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
double xm = e.getMinX();
if( lexCompareEdges( xm, x ) > 0 ) {
/*
* The edges are sorted by xmin, and this xmin exceeds
* the x value of the vertex. No more interactions.
*/
return;
}
Vertex v1 = e.getV1();
Vertex v2 = e.getV2();
if( Loose.zero(
vp.distToLine( v1.getPosition(), v2.getPosition() ) ) ) {
if( Loose.zero( vp.dist( v1.getPosition() ) ) ||
Loose.zero( vp.dist( v2.getPosition() ) ) ) {
// Don't split if too near endpoints.
continue;
}
// Create the new edge instance.
Edge nedge = new Edge( this, vert, v2 );
// We don't need to fix up v1 -- it can still point
// to the same edge.
// Fix up v2.
v2.swapEdge( v1, nedge );
// Fix up the edge object -- it now points to the
// intervening edge.
e.v2 = vert;
// Insert the new edge.
edges.removeElementAt( idx );
insertEdge_Simple( nedge );
insertEdge_Simple( e );
// Update the adjacencies for the splitting vertex
vert.insertEdge( e );
vert.insertEdge( nedge );
// That's it.
return;
}
}
}
/*
* The "correct" version of inserting a vertex. Make sure the
* map stays consistent.
*/
final Vertex getVertex_Complex( Point pt )
{
Vertex vert = getVertex_Simple( pt );
splitEdgesByVertex( vert );
return vert;
}
/*
* The publically-accessible version.
*/
public final Vertex insertVertex( Point pt )
{
return getVertex_Complex( pt );
}
/*
* Applying a motion made up only of uniform scales and translations,
* Angles don't change. So we can just transform each vertex.
*/
void applyTrivialRigidMotion( Transform T )
{
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
vert.pos = T.apply( vert.getPosition() );
}
}
public void scale( double s )
{
applyTrivialRigidMotion( Transform.scale( s ) );
}
public void translate( double x, double y )
{
applyTrivialRigidMotion( Transform.translate( x, y ) );
}
/*
* In the general case, the vertices and edges must be re-sorted.
*/
void applyGeneralRigidMotion( Transform T )
{
// Transform all the vertices.
for( Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
Vertex vert = (Vertex)( e.nextElement() );
vert.applyRigidMotion( T );
}
// Now sort everything.
sortVertices();
sortEdges();
}
public void transformMap( Transform T )
{
applyGeneralRigidMotion( T );
}
/*
* Transform a single vertex.
*/
public void transformVertex( Vertex v, Transform T )
{
// This isn't entirely trivial:
// 1. Transform the vertex itself and recalculate the neighbour
// angles.
// 2. For each vertex adjacent to this one, reinsert the connecting
// edge into the other vertex's neighbour list.
// 3. Reinsert the vertex into the map's vertex list -- its
// x position may have changed.
// 4. Re-sort the edge list, since edges which began at the
// transformed vertex may shift in the edge list.
//
// Right now most of this, especially steps 3 and 4, are done
// in the obvious, slow way. With more careful programming, we
// could break the process down further and do some parts faster,
// like searching for the vertex's new position relative to its
// current position. At this point, however, that's not a huge
// win.
// Transform the position of the vertex.
v.applyRigidMotion( T );
// Reorganize the vertices adjacent to this vertex.
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex other = edge.getOther( v );
other.removeEdge( edge );
other.insertEdge( edge );
}
// This vertex's x position may have changed. Reposition
// it in the array of vertices.
vertices.removeElement( v );
Point pt = v.getPosition();
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex vo = (Vertex)( vertices.elementAt( idx ) );
Point cur = vo.getPosition();
int cmp = lexComparePoints( pt, cur );
if( cmp < 0 ) {
vertices.insertElementAt( v, idx );
return;
}
}
vertices.addElement( v );
// Sigh -- I guess resort the edges.
sortEdges();
}
/*
* Given another vector of vertices, add them to the vertices of the
* current map. We can do this in linear time with a simple merge
* algorithm. Note that we want to coalesce identical vertices to
* eliminate duplicates.
*/
private void mergeVertices( Vector your_verts )
{
Vector my_verts = vertices;
int my_size = my_verts.size();
int your_size = your_verts.size();
vertices = new Vector( my_size + your_size );
int my_i = 0;
int your_i = 0;
while( true ) {
if( my_i == my_size ) {
if( your_i == your_size ) {
// done!
return;
} else {
Vertex your_v = (Vertex)( your_verts.elementAt( your_i ) );
Vertex nv = new Vertex( this, your_v.getPosition() );
vertices.addElement( nv );
your_v.copy = nv;
++your_i;
}
} else {
if( your_i == your_size ) {
vertices.addElement( my_verts.elementAt( my_i ) );
++my_i;
} else {
// Darn -- have to actually merge.
Vertex my_v = (Vertex)( my_verts.elementAt( my_i ) );
Vertex your_v = (Vertex)( your_verts.elementAt( your_i ) );
int cmp = lexComparePoints(
my_v.getPosition(), your_v.getPosition() );
if( cmp < 0 ) {
// my_v goes first.
vertices.addElement( my_v );
++my_i;
} else if( cmp == 0 ) {
// It's a toss up.
vertices.addElement( my_v );
your_v.copy = my_v;
++my_i;
++your_i;
} else if( cmp > 0 ) {
// your_v goes first.
Vertex nv = new Vertex( this, your_v.getPosition() );
vertices.addElement( nv );
your_v.copy = nv;
++your_i;
}
}
}
}
}
/*
* Merge two maps. The bread and butter of the Map class. This is a
* complicated computational geometry algorithm with a long and
* glorious tradition :^)
*
* The goal is to form a map from the union of the two sets of
* vertices (eliminating duplicates) and the union of the two sets
* of edges (splitting edges whenever intersections occur).
*
* There are very efficient ways to do this, reporting edge-edge
* intersections using a plane-sweep algorithm. Implementing
* this merge code in all its glory would be too much work. Since
* I have to use all my own code, I'm going to resort to a simplified
* (and slower) version of the algorithm.
*/
public void mergeMap( Map other, boolean consume )
{
/*
* Sanity checks to use when debugging.
boolean at_start = verify();
if( !at_start ) {
System.err.println( "Bad at start." );
}
if( !other.verify() ) {
System.err.println( "Other bad at start." );
}
*/
// Here's how I'm going to do this.
//
// 1. Check all intersections between edges from this map
// and from the other map. Record the positions of the
// intersections.
//
// 2. For each intersection position, get the vertex in both
// maps, forcing edges to split where the intersections will
// occur.
//
// 3. Merge the vertices.
//
// 4. Add the edges in the trivial way, since now there will
// be no intersections.
//
// Yech -- pretty slow. But I shudder at the thought of
// doing it with maximal efficiency.
//
// In practice, this routine has proven to be efficient enough
// for the Islamic design tool. Phew!
// Step 0 -- setup.
// Create a vector to hold the intersections.
if( !consume ) {
// Copy the other map so we don't destroy it.
other = (Map)( other.clone() );
}
Vector intersections = new Vector();
// Step 1
for( Enumeration e = other.getEdges(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
// To check all intersections of this edge with edges in
// the current map, we can use the optimization that
// edges are stored in sorted order by min x. So at the
// very least, skip the suffix of edges whose minimum x values
// are past the max x of the edge to check.
Point ep = edge.getV1().getPosition();
Point eq = edge.getV2().getPosition();
double exm = Math.max( ep.getX(), eq.getX() );
for( Enumeration me = getEdges(); me.hasMoreElements(); ) {
Edge cur = (Edge)( me.nextElement() );
Point cp = cur.getV1().getPosition();
Point cq = cur.getV2().getPosition();
if( lexCompareEdges( cur.getMinX(), exm ) > 0 ) {
break;
}
Point ipt = Intersect.getTrueIntersection( ep, eq, cp, cq );
if( ipt != null ) {
intersections.addElement( ipt );
}
}
}
// Step 2
for( Enumeration e = intersections.elements(); e.hasMoreElements(); ) {
Point p = (Point)( e.nextElement() );
getVertex_Complex( p );
other.getVertex_Complex( p );
}
// Step 3
mergeVertices( other.vertices );
// Step 4
for( Enumeration e = other.edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
Edge ne = new Edge( this, v1, v2 );
// Rather than using insertEdge_Simple, we tack all new edges
// to the end of the edge list...
edges.addElement( ne );
v1.insertEdge( ne );
v2.insertEdge( ne );
}
// ... and then sort everything together for speed.
sortEdges();
// I guess that's it!
/*
if( at_start && !verify() ) {
System.err.println( "it went bad." );
dump( System.err );
}
*/
}
public void mergeMap( Map other )
{
mergeMap( other, false );
}
/*
* A simpler merge routine that assumes that the two maps
* don't interact except at vertices, so edges don't need to
* be checked for intersections.
*/
public void mergeSimple( Map other )
{
// System.err.println( "mergeSimple begin" );
mergeVertices( other.vertices );
for( Enumeration e = other.getEdges(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
// insertEdge( edge.getV1().copy,<SUF>
Edge nedge = new Edge( this, v1, v2 );
v1.insertEdge( nedge );
v2.insertEdge( nedge );
edges.addElement( nedge );
}
sortEdges();
}
/*
* It's often the case that we want to merge a transformed copy of
* a map into another map, or even a collection of transformed copies.
* Since transforming a map requires a slow cloning, we can save lots
* of time and memory by transforming and merging simultaneously.
* Here, we transform vertices as they are put into the current map.
*/
public void mergeSimpleMany( Map other, Vector transforms )
{
for( Enumeration e = transforms.elements(); e.hasMoreElements(); ) {
Transform T = (Transform)( e.nextElement() );
for( Enumeration v = other.getVertices(); v.hasMoreElements(); ) {
Vertex vert = (Vertex)( v.nextElement() );
vert.copy = getVertex_Simple( T.apply( vert.getPosition() ) );
}
for( Enumeration v = other.getEdges(); v.hasMoreElements(); ) {
Edge edge = (Edge)( v.nextElement() );
Vertex v1 = edge.getV1().copy;
Vertex v2 = edge.getV2().copy;
Edge nedge = new Edge( this, v1, v2 );
v1.insertEdge( nedge );
v2.insertEdge( nedge );
edges.addElement( nedge );
}
}
sortEdges();
}
public Edge getLine()
{
index=(int) (Math.random()*edges.size());
Edge edge = (Edge)( edges.elementAt( index ) );
return edge;
}
/*
* Print a text version of the map.
*/
public void dump( java.io.PrintStream ow )
{
ow.println( "" + vertices.size() + " vertices." );
ow.println( "" + edges.size() + " edges.\n" );
for( int idx = 0; idx < vertices.size(); ++idx ) {
Vertex v = (Vertex)( vertices.elementAt( idx ) );
ow.println( "vertex " + idx + " at " + v.getPosition() );
for( Enumeration e = v.neighbours(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
ow.println( "\t--> " + edges.indexOf( edge ) );
}
}
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge edge = (Edge)( edges.elementAt( idx ) );
ow.println( "edge " + idx +
" from " + vertices.indexOf( edge.getV1() ) +
" to " + vertices.indexOf( edge.getV2() ) );
}
}
/*
* A big 'ole sanity check for maps. Throw together a whole collection
* of consistency checks. When debugging maps, call early and call often.
*
* It would probably be better to make this function provide the error
* messages through a return value or exception, but whatever.
*/
public boolean verify()
{
boolean good = true;
// Make sure there are no trivial edges.
for( int idx = 0; idx < edges.size(); ++idx ) {
Edge e = (Edge)( edges.elementAt( idx ) );
if( e.getV1().equals( e.getV2() ) ) {
System.err.println( "Trivial edge " + idx );
good = false;
}
}
for( Enumeration e = edges.elements(); e.hasMoreElements(); ) {
Edge edge = (Edge)( e.nextElement() );
// Make sure that for every edge, the edge's endpoints
// are know vertices in the map.
if( !vertices.contains( edge.getV1() ) ) {
System.err.println( "edge " +
edges.indexOf( edge ) + " V1 not in vertex list." );
good = false;
}
if( !vertices.contains( edge.getV2() ) ) {
System.err.println( "edge " +
edges.indexOf( edge ) + " V2 not in vertex list." );
good = false;
}
// Make sure that the edge's endpoints know about the
// edge, and that the edge is the only connection between
// the two endpoints.
Edge ed = edge.getV1().getNeighbour( edge.getV2() );
if( ed == null ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not found in vertex v1 neighbours for vertex " +
vertices.indexOf( edge.getV1() ) );
good = false;
}
if( !ed.equals( edge ) ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not matched in vertex v1 neighbours for vertex " +
vertices.indexOf( edge.getV1() ) );
good = false;
}
ed = edge.getV2().getNeighbour( edge.getV1() );
if( ed == null ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not found in vertex v2 neighbours for vertex " +
vertices.indexOf( edge.getV2() ) );
good = false;
}
if( !ed.equals( edge ) ) {
System.err.println( "edge " + edges.indexOf( edge ) +
" not matched in vertex v2 neighbours for vertex " +
vertices.indexOf( edge.getV2() ) );
good = false;
}
}
// Make sure the edges are in sorted order.
for( int idx = 1; idx < edges.size(); ++idx ) {
Edge e1 = (Edge)( edges.elementAt( idx - 1 ) );
Edge e2 = (Edge)( edges.elementAt( idx ) );
double e1x = e1.getMinX();
double e2x = e2.getMinX();
if( e1x > (e2x + Loose.TOL) ) {
System.err.println( "Sortedness check failed for edges." );
good = false;
}
}
// Make sure the vertices are in sorted order.
for( int idx = 1; idx < vertices.size(); ++idx ) {
Vertex v1 = (Vertex)( vertices.elementAt( idx - 1 ) );
Vertex v2 = (Vertex)( vertices.elementAt( idx ) );
int cmp = lexComparePoints( v1.getPosition(), v2.getPosition() );
if( cmp == 0 ) {
System.err.println( "Duplicate vertices." );
good = false;
} else if( cmp > 0 ) {
System.err.println( "Sortedness check failed for vertices." );
good = false;
}
}
// Other possible checks:
// - Make sure there's no edge from a vertex to itself.
return good;
}
}
|
193877_8 | /**
* This file is part of RefactorGuidance project. Which explores possibilities to generate context based
* instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students)
*
* Copyright (C) 2018, Patrick de Beer, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package analysis.context;
import aig.AdaptiveInstructionGraph;
import aig.CodeContext;
import analysis.ICodeAnalyzer;
import analysis.MethodAnalyzer.ClassMethodFinder;
import analysis.dataflow.MethodDataFlowAnalyzer;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
/**
* Class builds up a set of context detectors that are needed to detect contextual situations
* in a given adaptive instruction graph. The list of detectors can be provided to the procedural
* guidance generator
*/
public class ContextDetectorSetBuilder {
private AdaptiveInstructionGraph _aig = null;
private ContextConfiguration _analyzerConfig = null;
private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>();
private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>();
public void SetAIT(AdaptiveInstructionGraph aig) {
setAIT(aig);
}
public void setAIT(AdaptiveInstructionGraph aig) {
this._aig = aig;
}
public List<IContextDetector> getContextDetectors() throws Exception {
if(_analyzerConfig == null) {
throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first");
}
EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph();
String refactoringProcessName = this._aig.getRefactorMechanic();
if(refactoringProcessName.contentEquals("Rename Method"))
{
// Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen
// They can be directly initialized if contextanalyzerconfiguration object is present
// voor deze specifieke method
// uitlezen cu + methodname of line numers
// initieren ClassMethodFinder analyzer (en evt. andere analyzers)
// instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector
// intern weet op te vragen.
// Voeg de analuzers toe aan ContextAnalyzerCOnfiguration
BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input
}
else
if(refactoringProcessName.contentEquals("Extract Method") )
{
BuildExtractMethodContextDetectors(completeCodeContext);
}
return this._contextDetectors;
}
/**
* Through the returned configuration object, the created analyzers can be accessed
* - to initialize from the outside
* - to be used by the detectors to access necessary information
* @return
*/
public ContextConfiguration getContextAnalyzerConfiguration()
{
return _analyzerConfig;
}
public void setContextConfiguration(ContextConfiguration config)
{
_analyzerConfig = config;
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
_analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer());
_analyzerConfig.getMethodDataFlowAnalyzer().initialize(
_analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(),
_analyzerConfig.getCodeSection());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
/**
* A set of context detectors is build based on the context set that is provided.
* The @ContextConfiguration object is used to provide detectors with necessary input in a generic way
*
* @param completeCodeContext Context detectors that should be instantiated
* @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers
*/
private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext,
ContextConfiguration analyzerConfig)
{
if (ContextDetectorForAllContextDecisions(completeCodeContext)) {
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) {
Class<?> classCtxt = Class.forName("analysis.context." + context.name());
Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration");
Constructor<?> constructor = classCtxt.getConstructor(classConfig);
IContextDetector instance =
(IContextDetector) constructor.newInstance(analyzerConfig);
_contextDetectors.add(instance);
}
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
/**
* Internally used to validate if all requested detectors in the context set are actually
* present as classes in our java project
*
* @param completeCodeContext
* @return True, when all necessary classes could be found
*/
private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) {
boolean allDefined = true;
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString()))
Class.forName("analysis.context." + context.name());
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println("class " + cnfe.getMessage() + " not defined");
allDefined = false;
}
return allDefined;
}
public void setConfiguration(ContextConfiguration configuration) {
this._analyzerConfig = configuration;
}
}
| the-refactorers/RefactorGuidanceTool | src/main/java/analysis/context/ContextDetectorSetBuilder.java | 2,084 | // intern weet op te vragen. | line_comment | nl | /**
* This file is part of RefactorGuidance project. Which explores possibilities to generate context based
* instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students)
*
* Copyright (C) 2018, Patrick de Beer, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, 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 warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package analysis.context;
import aig.AdaptiveInstructionGraph;
import aig.CodeContext;
import analysis.ICodeAnalyzer;
import analysis.MethodAnalyzer.ClassMethodFinder;
import analysis.dataflow.MethodDataFlowAnalyzer;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
/**
* Class builds up a set of context detectors that are needed to detect contextual situations
* in a given adaptive instruction graph. The list of detectors can be provided to the procedural
* guidance generator
*/
public class ContextDetectorSetBuilder {
private AdaptiveInstructionGraph _aig = null;
private ContextConfiguration _analyzerConfig = null;
private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>();
private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>();
public void SetAIT(AdaptiveInstructionGraph aig) {
setAIT(aig);
}
public void setAIT(AdaptiveInstructionGraph aig) {
this._aig = aig;
}
public List<IContextDetector> getContextDetectors() throws Exception {
if(_analyzerConfig == null) {
throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first");
}
EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph();
String refactoringProcessName = this._aig.getRefactorMechanic();
if(refactoringProcessName.contentEquals("Rename Method"))
{
// Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen
// They can be directly initialized if contextanalyzerconfiguration object is present
// voor deze specifieke method
// uitlezen cu + methodname of line numers
// initieren ClassMethodFinder analyzer (en evt. andere analyzers)
// instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector
// intern weet<SUF>
// Voeg de analuzers toe aan ContextAnalyzerCOnfiguration
BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input
}
else
if(refactoringProcessName.contentEquals("Extract Method") )
{
BuildExtractMethodContextDetectors(completeCodeContext);
}
return this._contextDetectors;
}
/**
* Through the returned configuration object, the created analyzers can be accessed
* - to initialize from the outside
* - to be used by the detectors to access necessary information
* @return
*/
public ContextConfiguration getContextAnalyzerConfiguration()
{
return _analyzerConfig;
}
public void setContextConfiguration(ContextConfiguration config)
{
_analyzerConfig = config;
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
_analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer());
_analyzerConfig.getMethodDataFlowAnalyzer().initialize(
_analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(),
_analyzerConfig.getCodeSection());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
/**
* A set of context detectors is build based on the context set that is provided.
* The @ContextConfiguration object is used to provide detectors with necessary input in a generic way
*
* @param completeCodeContext Context detectors that should be instantiated
* @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers
*/
private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext,
ContextConfiguration analyzerConfig)
{
if (ContextDetectorForAllContextDecisions(completeCodeContext)) {
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) {
Class<?> classCtxt = Class.forName("analysis.context." + context.name());
Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration");
Constructor<?> constructor = classCtxt.getConstructor(classConfig);
IContextDetector instance =
(IContextDetector) constructor.newInstance(analyzerConfig);
_contextDetectors.add(instance);
}
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
/**
* Internally used to validate if all requested detectors in the context set are actually
* present as classes in our java project
*
* @param completeCodeContext
* @return True, when all necessary classes could be found
*/
private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) {
boolean allDefined = true;
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString()))
Class.forName("analysis.context." + context.name());
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println("class " + cnfe.getMessage() + " not defined");
allDefined = false;
}
return allDefined;
}
public void setConfiguration(ContextConfiguration configuration) {
this._analyzerConfig = configuration;
}
}
|
25486_18 | // Copyright 2014 theaigames.com ([email protected])
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
package main;
import io.IORobot;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.SwingUtilities;
import java.lang.InterruptedException;
import java.lang.Thread;
import java.util.zip.*;
import move.AttackTransferMove;
import move.MoveResult;
import move.PlaceArmiesMove;
import org.bson.types.ObjectId;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
public class RunGame
{
LinkedList<MoveResult> fullPlayedGame;
LinkedList<MoveResult> player1PlayedGame;
LinkedList<MoveResult> player2PlayedGame;
int gameIndex = 1;
String playerName1, playerName2;
final String gameId,
bot1Id, bot2Id,
bot1Dir, bot2Dir;
Engine engine;
DB db;
public static void main(String args[]) throws Exception
{
RunGame run = new RunGame(args);
run.go();
}
public RunGame(String args[])
{
this.gameId = args[0];
this.bot1Id = args[1];
this.bot2Id = args[2];
this.bot1Dir = args[3];
this.bot2Dir = args[4];
this.playerName1 = "player1";
this.playerName2 = "player2";
}
private void go() throws IOException, InterruptedException
{
System.out.println("starting game " + gameId);
Map initMap, map;
Player player1, player2;
IORobot bot1, bot2;
int startingArmies;
db = new MongoClient("localhost", 27017).getDB("test");
//setup the bots
bot1 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer1 " + bot1Dir);
bot2 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer2 " + bot2Dir);
startingArmies = 5;
player1 = new Player(playerName1, bot1, startingArmies);
player2 = new Player(playerName2, bot2, startingArmies);
//setup the map
initMap = makeInitMap();
map = setupMap(initMap);
//start the engine
this.engine = new Engine(map, player1, player2);
//send the bots the info they need to start
bot1.writeInfo("settings your_bot " + player1.getName());
bot1.writeInfo("settings opponent_bot " + player2.getName());
bot2.writeInfo("settings your_bot " + player2.getName());
bot2.writeInfo("settings opponent_bot " + player1.getName());
sendSetupMapInfo(player1.getBot(), initMap);
sendSetupMapInfo(player2.getBot(), initMap);
this.engine.distributeStartingRegions(); //decide the player's starting regions
this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions)
this.engine.sendAllInfo();
//play the game
while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= 100)
{
bot1.addToDump("Round " + this.engine.getRoundNr() + "\n");
bot2.addToDump("Round " + this.engine.getRoundNr() + "\n");
this.engine.playRound();
}
fullPlayedGame = this.engine.getFullPlayedGame();
player1PlayedGame = this.engine.getPlayer1PlayedGame();
player2PlayedGame = this.engine.getPlayer2PlayedGame();
finish(bot1, bot2);
}
//aanpassen en een QPlayer class maken? met eigen finish
private void finish(IORobot bot1, IORobot bot2) throws InterruptedException
{
bot1.finish();
Thread.sleep(200);
bot2.finish();
Thread.sleep(200);
Thread.sleep(200);
// write everything
// String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer());
this.saveGame(bot1, bot2);
System.exit(0);
}
//tijdelijk handmatig invoeren
private Map makeInitMap()
{
Map map = new Map();
SuperRegion northAmerica = new SuperRegion(1, 5);
SuperRegion southAmerica = new SuperRegion(2, 2);
SuperRegion europe = new SuperRegion(3, 5);
SuperRegion afrika = new SuperRegion(4, 3);
SuperRegion azia = new SuperRegion(5, 7);
SuperRegion australia = new SuperRegion(6, 2);
Region region1 = new Region(1, northAmerica);
Region region2 = new Region(2, northAmerica);
Region region3 = new Region(3, northAmerica);
Region region4 = new Region(4, northAmerica);
Region region5 = new Region(5, northAmerica);
Region region6 = new Region(6, northAmerica);
Region region7 = new Region(7, northAmerica);
Region region8 = new Region(8, northAmerica);
Region region9 = new Region(9, northAmerica);
Region region10 = new Region(10, southAmerica);
Region region11 = new Region(11, southAmerica);
Region region12 = new Region(12, southAmerica);
Region region13 = new Region(13, southAmerica);
Region region14 = new Region(14, europe);
Region region15 = new Region(15, europe);
Region region16 = new Region(16, europe);
Region region17 = new Region(17, europe);
Region region18 = new Region(18, europe);
Region region19 = new Region(19, europe);
Region region20 = new Region(20, europe);
Region region21 = new Region(21, afrika);
Region region22 = new Region(22, afrika);
Region region23 = new Region(23, afrika);
Region region24 = new Region(24, afrika);
Region region25 = new Region(25, afrika);
Region region26 = new Region(26, afrika);
Region region27 = new Region(27, azia);
Region region28 = new Region(28, azia);
Region region29 = new Region(29, azia);
Region region30 = new Region(30, azia);
Region region31 = new Region(31, azia);
Region region32 = new Region(32, azia);
Region region33 = new Region(33, azia);
Region region34 = new Region(34, azia);
Region region35 = new Region(35, azia);
Region region36 = new Region(36, azia);
Region region37 = new Region(37, azia);
Region region38 = new Region(38, azia);
Region region39 = new Region(39, australia);
Region region40 = new Region(40, australia);
Region region41 = new Region(41, australia);
Region region42 = new Region(42, australia);
region1.addNeighbor(region2);
region1.addNeighbor(region4);
region1.addNeighbor(region30);
region2.addNeighbor(region4);
region2.addNeighbor(region3);
region2.addNeighbor(region5);
region3.addNeighbor(region5);
region3.addNeighbor(region6);
region3.addNeighbor(region14);
region4.addNeighbor(region5);
region4.addNeighbor(region7);
region5.addNeighbor(region6);
region5.addNeighbor(region7);
region5.addNeighbor(region8);
region6.addNeighbor(region8);
region7.addNeighbor(region8);
region7.addNeighbor(region9);
region8.addNeighbor(region9);
region9.addNeighbor(region10);
region10.addNeighbor(region11);
region10.addNeighbor(region12);
region11.addNeighbor(region12);
region11.addNeighbor(region13);
region12.addNeighbor(region13);
region12.addNeighbor(region21);
region14.addNeighbor(region15);
region14.addNeighbor(region16);
region15.addNeighbor(region16);
region15.addNeighbor(region18);
region15.addNeighbor(region19);
region16.addNeighbor(region17);
region17.addNeighbor(region19);
region17.addNeighbor(region20);
region17.addNeighbor(region27);
region17.addNeighbor(region32);
region17.addNeighbor(region36);
region18.addNeighbor(region19);
region18.addNeighbor(region20);
region18.addNeighbor(region21);
region19.addNeighbor(region20);
region20.addNeighbor(region21);
region20.addNeighbor(region22);
region20.addNeighbor(region36);
region21.addNeighbor(region22);
region21.addNeighbor(region23);
region21.addNeighbor(region24);
region22.addNeighbor(region23);
region22.addNeighbor(region36);
region23.addNeighbor(region24);
region23.addNeighbor(region25);
region23.addNeighbor(region26);
region23.addNeighbor(region36);
region24.addNeighbor(region25);
region25.addNeighbor(region26);
region27.addNeighbor(region28);
region27.addNeighbor(region32);
region27.addNeighbor(region33);
region28.addNeighbor(region29);
region28.addNeighbor(region31);
region28.addNeighbor(region33);
region28.addNeighbor(region34);
region29.addNeighbor(region30);
region29.addNeighbor(region31);
region30.addNeighbor(region31);
region30.addNeighbor(region34);
region30.addNeighbor(region35);
region31.addNeighbor(region34);
region32.addNeighbor(region33);
region32.addNeighbor(region36);
region32.addNeighbor(region37);
region33.addNeighbor(region34);
region33.addNeighbor(region37);
region33.addNeighbor(region38);
region34.addNeighbor(region35);
region36.addNeighbor(region37);
region37.addNeighbor(region38);
region38.addNeighbor(region39);
region39.addNeighbor(region40);
region39.addNeighbor(region41);
region40.addNeighbor(region41);
region40.addNeighbor(region42);
region41.addNeighbor(region42);
map.add(region1); map.add(region2); map.add(region3);
map.add(region4); map.add(region5); map.add(region6);
map.add(region7); map.add(region8); map.add(region9);
map.add(region10); map.add(region11); map.add(region12);
map.add(region13); map.add(region14); map.add(region15);
map.add(region16); map.add(region17); map.add(region18);
map.add(region19); map.add(region20); map.add(region21);
map.add(region22); map.add(region23); map.add(region24);
map.add(region25); map.add(region26); map.add(region27);
map.add(region28); map.add(region29); map.add(region30);
map.add(region31); map.add(region32); map.add(region33);
map.add(region34); map.add(region35); map.add(region36);
map.add(region37); map.add(region38); map.add(region39);
map.add(region40); map.add(region41); map.add(region42);
map.add(northAmerica);
map.add(southAmerica);
map.add(europe);
map.add(afrika);
map.add(azia);
map.add(australia);
return map;
}
//Make every region neutral with 2 armies to start with
private Map setupMap(Map initMap)
{
Map map = initMap;
for(Region region : map.regions)
{
region.setPlayerName("neutral");
region.setArmies(2);
}
return map;
}
private void sendSetupMapInfo(Robot bot, Map initMap)
{
String setupSuperRegionsString, setupRegionsString, setupNeighborsString;
setupSuperRegionsString = getSuperRegionsString(initMap);
setupRegionsString = getRegionsString(initMap);
setupNeighborsString = getNeighborsString(initMap);
bot.writeInfo(setupSuperRegionsString);
// System.out.println(setupSuperRegionsString);
bot.writeInfo(setupRegionsString);
// System.out.println(setupRegionsString);
bot.writeInfo(setupNeighborsString);
// System.out.println(setupNeighborsString);
}
private String getSuperRegionsString(Map map)
{
String superRegionsString = "setup_map super_regions";
for(SuperRegion superRegion : map.superRegions)
{
int id = superRegion.getId();
int reward = superRegion.getArmiesReward();
superRegionsString = superRegionsString.concat(" " + id + " " + reward);
}
return superRegionsString;
}
private String getRegionsString(Map map)
{
String regionsString = "setup_map regions";
for(Region region : map.regions)
{
int id = region.getId();
int superRegionId = region.getSuperRegion().getId();
regionsString = regionsString.concat(" " + id + " " + superRegionId);
}
return regionsString;
}
//beetje inefficiente methode, maar kan niet sneller wss
private String getNeighborsString(Map map)
{
String neighborsString = "setup_map neighbors";
ArrayList<Point> doneList = new ArrayList<Point>();
for(Region region : map.regions)
{
int id = region.getId();
String neighbors = "";
for(Region neighbor : region.getNeighbors())
{
if(checkDoneList(doneList, id, neighbor.getId()))
{
neighbors = neighbors.concat("," + neighbor.getId());
doneList.add(new Point(id,neighbor.getId()));
}
}
if(neighbors.length() != 0)
{
neighbors = neighbors.replaceFirst(","," ");
neighborsString = neighborsString.concat(" " + id + neighbors);
}
}
return neighborsString;
}
private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId)
{
for(Point p : doneList)
if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId))
return false;
return true;
}
private String getPlayedGame(Player winner, String gameView)
{
StringBuffer out = new StringBuffer();
LinkedList<MoveResult> playedGame;
if(gameView.equals("player1"))
playedGame = player1PlayedGame;
else if(gameView.equals("player2"))
playedGame = player2PlayedGame;
else
playedGame = fullPlayedGame;
playedGame.removeLast();
int roundNr = 2;
out.append("map " + playedGame.getFirst().getMap().getMapString() + "\n");
out.append("round 1" + "\n");
for(MoveResult moveResult : playedGame)
{
if(moveResult != null)
{
if(moveResult.getMove() != null)
{
try {
PlaceArmiesMove plm = (PlaceArmiesMove) moveResult.getMove();
out.append(plm.getString() + "\n");
}
catch(Exception e) {
AttackTransferMove atm = (AttackTransferMove) moveResult.getMove();
out.append(atm.getString() + "\n");
}
out.append("map " + moveResult.getMap().getMapString() + "\n");
}
}
else
{
out.append("round " + roundNr + "\n");
roundNr++;
}
}
if(winner != null)
out.append(winner.getName() + " won\n");
else
out.append("Nobody won\n");
return out.toString();
}
private String compressGZip(String data, String outFile)
{
try {
FileOutputStream fos = new FileOutputStream(outFile);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
byte[] outBytes = data.getBytes("UTF-8");
gzos.write(outBytes, 0, outBytes.length);
gzos.finish();
gzos.close();
return outFile;
}
catch(IOException e) {
System.out.println(e);
return "";
}
}
/*
* MongoDB connection functions
*/
public void saveGame(IORobot bot1, IORobot bot2) {
Player winner = this.engine.winningPlayer();
int score = this.engine.getRoundNr() - 1;
DBCollection coll = db.getCollection("games");
DBObject queryDoc = new BasicDBObject()
.append("_id", new ObjectId(gameId));
ObjectId bot1ObjectId = new ObjectId(bot1Id);
ObjectId bot2ObjectId = new ObjectId(bot2Id);
ObjectId winnerId = null;
if(winner != null) {
winnerId = winner.getName() == playerName1 ? bot1ObjectId : bot2ObjectId;
}
//create game directory
String dir = "/var/www/theaigames/public/games/" + gameId;
new File(dir).mkdir();
DBObject updateDoc = new BasicDBObject()
.append("$set", new BasicDBObject()
.append("winner", winnerId)
.append("score", score)
.append("visualization",
compressGZip(
getPlayedGame(winner, "fullGame") +
getPlayedGame(winner, "player1") +
getPlayedGame(winner, "player2"),
dir + "/visualization"
)
)
.append("errors", new BasicDBObject()
.append(bot1Id, compressGZip(bot1.getStderr(), dir + "/bot1Errors"))
.append(bot2Id, compressGZip(bot2.getStderr(), dir + "/bot2Errors"))
)
.append("dump", new BasicDBObject()
.append(bot1Id, compressGZip(bot1.getDump(), dir + "/bot1Dump"))
.append(bot2Id, compressGZip(bot2.getDump(), dir + "/bot2Dump"))
)
.append("ranked", 0)
);
coll.findAndModify(queryDoc, updateDoc);
}
}
| theaigames/conquest-engine | main/RunGame.java | 5,649 | //aanpassen en een QPlayer class maken? met eigen finish
| line_comment | nl | // Copyright 2014 theaigames.com ([email protected])
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
package main;
import io.IORobot;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.SwingUtilities;
import java.lang.InterruptedException;
import java.lang.Thread;
import java.util.zip.*;
import move.AttackTransferMove;
import move.MoveResult;
import move.PlaceArmiesMove;
import org.bson.types.ObjectId;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
public class RunGame
{
LinkedList<MoveResult> fullPlayedGame;
LinkedList<MoveResult> player1PlayedGame;
LinkedList<MoveResult> player2PlayedGame;
int gameIndex = 1;
String playerName1, playerName2;
final String gameId,
bot1Id, bot2Id,
bot1Dir, bot2Dir;
Engine engine;
DB db;
public static void main(String args[]) throws Exception
{
RunGame run = new RunGame(args);
run.go();
}
public RunGame(String args[])
{
this.gameId = args[0];
this.bot1Id = args[1];
this.bot2Id = args[2];
this.bot1Dir = args[3];
this.bot2Dir = args[4];
this.playerName1 = "player1";
this.playerName2 = "player2";
}
private void go() throws IOException, InterruptedException
{
System.out.println("starting game " + gameId);
Map initMap, map;
Player player1, player2;
IORobot bot1, bot2;
int startingArmies;
db = new MongoClient("localhost", 27017).getDB("test");
//setup the bots
bot1 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer1 " + bot1Dir);
bot2 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer2 " + bot2Dir);
startingArmies = 5;
player1 = new Player(playerName1, bot1, startingArmies);
player2 = new Player(playerName2, bot2, startingArmies);
//setup the map
initMap = makeInitMap();
map = setupMap(initMap);
//start the engine
this.engine = new Engine(map, player1, player2);
//send the bots the info they need to start
bot1.writeInfo("settings your_bot " + player1.getName());
bot1.writeInfo("settings opponent_bot " + player2.getName());
bot2.writeInfo("settings your_bot " + player2.getName());
bot2.writeInfo("settings opponent_bot " + player1.getName());
sendSetupMapInfo(player1.getBot(), initMap);
sendSetupMapInfo(player2.getBot(), initMap);
this.engine.distributeStartingRegions(); //decide the player's starting regions
this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions)
this.engine.sendAllInfo();
//play the game
while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= 100)
{
bot1.addToDump("Round " + this.engine.getRoundNr() + "\n");
bot2.addToDump("Round " + this.engine.getRoundNr() + "\n");
this.engine.playRound();
}
fullPlayedGame = this.engine.getFullPlayedGame();
player1PlayedGame = this.engine.getPlayer1PlayedGame();
player2PlayedGame = this.engine.getPlayer2PlayedGame();
finish(bot1, bot2);
}
//aanpassen en<SUF>
private void finish(IORobot bot1, IORobot bot2) throws InterruptedException
{
bot1.finish();
Thread.sleep(200);
bot2.finish();
Thread.sleep(200);
Thread.sleep(200);
// write everything
// String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer());
this.saveGame(bot1, bot2);
System.exit(0);
}
//tijdelijk handmatig invoeren
private Map makeInitMap()
{
Map map = new Map();
SuperRegion northAmerica = new SuperRegion(1, 5);
SuperRegion southAmerica = new SuperRegion(2, 2);
SuperRegion europe = new SuperRegion(3, 5);
SuperRegion afrika = new SuperRegion(4, 3);
SuperRegion azia = new SuperRegion(5, 7);
SuperRegion australia = new SuperRegion(6, 2);
Region region1 = new Region(1, northAmerica);
Region region2 = new Region(2, northAmerica);
Region region3 = new Region(3, northAmerica);
Region region4 = new Region(4, northAmerica);
Region region5 = new Region(5, northAmerica);
Region region6 = new Region(6, northAmerica);
Region region7 = new Region(7, northAmerica);
Region region8 = new Region(8, northAmerica);
Region region9 = new Region(9, northAmerica);
Region region10 = new Region(10, southAmerica);
Region region11 = new Region(11, southAmerica);
Region region12 = new Region(12, southAmerica);
Region region13 = new Region(13, southAmerica);
Region region14 = new Region(14, europe);
Region region15 = new Region(15, europe);
Region region16 = new Region(16, europe);
Region region17 = new Region(17, europe);
Region region18 = new Region(18, europe);
Region region19 = new Region(19, europe);
Region region20 = new Region(20, europe);
Region region21 = new Region(21, afrika);
Region region22 = new Region(22, afrika);
Region region23 = new Region(23, afrika);
Region region24 = new Region(24, afrika);
Region region25 = new Region(25, afrika);
Region region26 = new Region(26, afrika);
Region region27 = new Region(27, azia);
Region region28 = new Region(28, azia);
Region region29 = new Region(29, azia);
Region region30 = new Region(30, azia);
Region region31 = new Region(31, azia);
Region region32 = new Region(32, azia);
Region region33 = new Region(33, azia);
Region region34 = new Region(34, azia);
Region region35 = new Region(35, azia);
Region region36 = new Region(36, azia);
Region region37 = new Region(37, azia);
Region region38 = new Region(38, azia);
Region region39 = new Region(39, australia);
Region region40 = new Region(40, australia);
Region region41 = new Region(41, australia);
Region region42 = new Region(42, australia);
region1.addNeighbor(region2);
region1.addNeighbor(region4);
region1.addNeighbor(region30);
region2.addNeighbor(region4);
region2.addNeighbor(region3);
region2.addNeighbor(region5);
region3.addNeighbor(region5);
region3.addNeighbor(region6);
region3.addNeighbor(region14);
region4.addNeighbor(region5);
region4.addNeighbor(region7);
region5.addNeighbor(region6);
region5.addNeighbor(region7);
region5.addNeighbor(region8);
region6.addNeighbor(region8);
region7.addNeighbor(region8);
region7.addNeighbor(region9);
region8.addNeighbor(region9);
region9.addNeighbor(region10);
region10.addNeighbor(region11);
region10.addNeighbor(region12);
region11.addNeighbor(region12);
region11.addNeighbor(region13);
region12.addNeighbor(region13);
region12.addNeighbor(region21);
region14.addNeighbor(region15);
region14.addNeighbor(region16);
region15.addNeighbor(region16);
region15.addNeighbor(region18);
region15.addNeighbor(region19);
region16.addNeighbor(region17);
region17.addNeighbor(region19);
region17.addNeighbor(region20);
region17.addNeighbor(region27);
region17.addNeighbor(region32);
region17.addNeighbor(region36);
region18.addNeighbor(region19);
region18.addNeighbor(region20);
region18.addNeighbor(region21);
region19.addNeighbor(region20);
region20.addNeighbor(region21);
region20.addNeighbor(region22);
region20.addNeighbor(region36);
region21.addNeighbor(region22);
region21.addNeighbor(region23);
region21.addNeighbor(region24);
region22.addNeighbor(region23);
region22.addNeighbor(region36);
region23.addNeighbor(region24);
region23.addNeighbor(region25);
region23.addNeighbor(region26);
region23.addNeighbor(region36);
region24.addNeighbor(region25);
region25.addNeighbor(region26);
region27.addNeighbor(region28);
region27.addNeighbor(region32);
region27.addNeighbor(region33);
region28.addNeighbor(region29);
region28.addNeighbor(region31);
region28.addNeighbor(region33);
region28.addNeighbor(region34);
region29.addNeighbor(region30);
region29.addNeighbor(region31);
region30.addNeighbor(region31);
region30.addNeighbor(region34);
region30.addNeighbor(region35);
region31.addNeighbor(region34);
region32.addNeighbor(region33);
region32.addNeighbor(region36);
region32.addNeighbor(region37);
region33.addNeighbor(region34);
region33.addNeighbor(region37);
region33.addNeighbor(region38);
region34.addNeighbor(region35);
region36.addNeighbor(region37);
region37.addNeighbor(region38);
region38.addNeighbor(region39);
region39.addNeighbor(region40);
region39.addNeighbor(region41);
region40.addNeighbor(region41);
region40.addNeighbor(region42);
region41.addNeighbor(region42);
map.add(region1); map.add(region2); map.add(region3);
map.add(region4); map.add(region5); map.add(region6);
map.add(region7); map.add(region8); map.add(region9);
map.add(region10); map.add(region11); map.add(region12);
map.add(region13); map.add(region14); map.add(region15);
map.add(region16); map.add(region17); map.add(region18);
map.add(region19); map.add(region20); map.add(region21);
map.add(region22); map.add(region23); map.add(region24);
map.add(region25); map.add(region26); map.add(region27);
map.add(region28); map.add(region29); map.add(region30);
map.add(region31); map.add(region32); map.add(region33);
map.add(region34); map.add(region35); map.add(region36);
map.add(region37); map.add(region38); map.add(region39);
map.add(region40); map.add(region41); map.add(region42);
map.add(northAmerica);
map.add(southAmerica);
map.add(europe);
map.add(afrika);
map.add(azia);
map.add(australia);
return map;
}
//Make every region neutral with 2 armies to start with
private Map setupMap(Map initMap)
{
Map map = initMap;
for(Region region : map.regions)
{
region.setPlayerName("neutral");
region.setArmies(2);
}
return map;
}
private void sendSetupMapInfo(Robot bot, Map initMap)
{
String setupSuperRegionsString, setupRegionsString, setupNeighborsString;
setupSuperRegionsString = getSuperRegionsString(initMap);
setupRegionsString = getRegionsString(initMap);
setupNeighborsString = getNeighborsString(initMap);
bot.writeInfo(setupSuperRegionsString);
// System.out.println(setupSuperRegionsString);
bot.writeInfo(setupRegionsString);
// System.out.println(setupRegionsString);
bot.writeInfo(setupNeighborsString);
// System.out.println(setupNeighborsString);
}
private String getSuperRegionsString(Map map)
{
String superRegionsString = "setup_map super_regions";
for(SuperRegion superRegion : map.superRegions)
{
int id = superRegion.getId();
int reward = superRegion.getArmiesReward();
superRegionsString = superRegionsString.concat(" " + id + " " + reward);
}
return superRegionsString;
}
private String getRegionsString(Map map)
{
String regionsString = "setup_map regions";
for(Region region : map.regions)
{
int id = region.getId();
int superRegionId = region.getSuperRegion().getId();
regionsString = regionsString.concat(" " + id + " " + superRegionId);
}
return regionsString;
}
//beetje inefficiente methode, maar kan niet sneller wss
private String getNeighborsString(Map map)
{
String neighborsString = "setup_map neighbors";
ArrayList<Point> doneList = new ArrayList<Point>();
for(Region region : map.regions)
{
int id = region.getId();
String neighbors = "";
for(Region neighbor : region.getNeighbors())
{
if(checkDoneList(doneList, id, neighbor.getId()))
{
neighbors = neighbors.concat("," + neighbor.getId());
doneList.add(new Point(id,neighbor.getId()));
}
}
if(neighbors.length() != 0)
{
neighbors = neighbors.replaceFirst(","," ");
neighborsString = neighborsString.concat(" " + id + neighbors);
}
}
return neighborsString;
}
private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId)
{
for(Point p : doneList)
if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId))
return false;
return true;
}
private String getPlayedGame(Player winner, String gameView)
{
StringBuffer out = new StringBuffer();
LinkedList<MoveResult> playedGame;
if(gameView.equals("player1"))
playedGame = player1PlayedGame;
else if(gameView.equals("player2"))
playedGame = player2PlayedGame;
else
playedGame = fullPlayedGame;
playedGame.removeLast();
int roundNr = 2;
out.append("map " + playedGame.getFirst().getMap().getMapString() + "\n");
out.append("round 1" + "\n");
for(MoveResult moveResult : playedGame)
{
if(moveResult != null)
{
if(moveResult.getMove() != null)
{
try {
PlaceArmiesMove plm = (PlaceArmiesMove) moveResult.getMove();
out.append(plm.getString() + "\n");
}
catch(Exception e) {
AttackTransferMove atm = (AttackTransferMove) moveResult.getMove();
out.append(atm.getString() + "\n");
}
out.append("map " + moveResult.getMap().getMapString() + "\n");
}
}
else
{
out.append("round " + roundNr + "\n");
roundNr++;
}
}
if(winner != null)
out.append(winner.getName() + " won\n");
else
out.append("Nobody won\n");
return out.toString();
}
private String compressGZip(String data, String outFile)
{
try {
FileOutputStream fos = new FileOutputStream(outFile);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
byte[] outBytes = data.getBytes("UTF-8");
gzos.write(outBytes, 0, outBytes.length);
gzos.finish();
gzos.close();
return outFile;
}
catch(IOException e) {
System.out.println(e);
return "";
}
}
/*
* MongoDB connection functions
*/
public void saveGame(IORobot bot1, IORobot bot2) {
Player winner = this.engine.winningPlayer();
int score = this.engine.getRoundNr() - 1;
DBCollection coll = db.getCollection("games");
DBObject queryDoc = new BasicDBObject()
.append("_id", new ObjectId(gameId));
ObjectId bot1ObjectId = new ObjectId(bot1Id);
ObjectId bot2ObjectId = new ObjectId(bot2Id);
ObjectId winnerId = null;
if(winner != null) {
winnerId = winner.getName() == playerName1 ? bot1ObjectId : bot2ObjectId;
}
//create game directory
String dir = "/var/www/theaigames/public/games/" + gameId;
new File(dir).mkdir();
DBObject updateDoc = new BasicDBObject()
.append("$set", new BasicDBObject()
.append("winner", winnerId)
.append("score", score)
.append("visualization",
compressGZip(
getPlayedGame(winner, "fullGame") +
getPlayedGame(winner, "player1") +
getPlayedGame(winner, "player2"),
dir + "/visualization"
)
)
.append("errors", new BasicDBObject()
.append(bot1Id, compressGZip(bot1.getStderr(), dir + "/bot1Errors"))
.append(bot2Id, compressGZip(bot2.getStderr(), dir + "/bot2Errors"))
)
.append("dump", new BasicDBObject()
.append(bot1Id, compressGZip(bot1.getDump(), dir + "/bot1Dump"))
.append(bot2Id, compressGZip(bot2.getDump(), dir + "/bot2Dump"))
)
.append("ranked", 0)
);
coll.findAndModify(queryDoc, updateDoc);
}
}
|
56702_3 |
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Calendar;
import java.util.Scanner;
//import nl.hu.ipass.persistence.BaseDAO;
public class App {
private static final String db_driv = "org.postgresql.Driver";
private static final String db_url = "jdbc:postgresql://localhost:5432/ipass";
private static final String db_user = "postgres";
private static final String db_pass = "Merlijn26";
private static Connection conn;
public static void main( String[] args ) throws SQLException {
try {
Class.forName(db_driv).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e1) {
e1.printStackTrace();
}
conn = DriverManager.getConnection(db_url, db_user, db_pass);
Scanner scanner = new Scanner(System.in);
while (true) {
Time huidige_tijd = new Time(Calendar.getInstance().getTime().getTime());
System.out.println("Voer uw sleutelcode in: ");
int code = scanner.nextInt();
String stringcode = Integer.toString(code);
if (stringcode.length() == 5) {
System.out.println("Ingevoerde sleutel: " + code);
System.out.println("Checking database...");
PreparedStatement p = conn.prepareStatement("SELECT "
+ "p.persoonsid, p.voornaam, p.achternaam, p.aanwezig "
+ "FROM persoon p, sleutel s "
+ "WHERE p.sleutelid = s.sleutelid "
+ "AND s.sleutelcode = ?");
p.setInt(1, code);
ResultSet rs = p.executeQuery();
if (rs.next()) {
// System.out.println("not supposed to be here!");
int persoonsid = rs.getInt("persoonsid");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
boolean aanwezig = rs.getBoolean("aanwezig");
String naam = voornaam + " " + achternaam;
System.out.println("Welkom " + naam);
// System.out.println(aanwezig);
PreparedStatement p6 = conn.prepareStatement("SELECT "
+ "MAX(aankomst_tijd) AS aankomst_tijd "
+ "FROM historie "
+ "WHERE persoonsid = ? "
+ "AND datum = (SELECT MAX(datum) "
+ " FROM historie "
+ " WHERE persoonsid = ?)");
p6.setInt(1, persoonsid);
p6.setInt(2, persoonsid);
ResultSet rs2 = p6.executeQuery();
rs2.next();
Time aankomst_tijd = rs2.getTime("aankomst_tijd");
System.out.println(aankomst_tijd);
//Select persoonsid:
System.out.println("Updating table persoon...");
if (aanwezig == false) {
//Update persoon where persoonsid = persoonsid hierboven
PreparedStatement p2 = conn.prepareStatement("UPDATE"
+ " persoon"
+ " SET aanwezig = true"
+ " WHERE persoonsid = ?");
p2.setInt(1, persoonsid);
p2.executeUpdate();
System.out.println(persoonsid + " " + naam + " staat nu op aanwezig");
System.out.println();
//inserten historie:
System.out.println("Inserting into historie...");
Date huidige_datum = new Date(Calendar.getInstance().getTime().getTime());
System.out.println(huidige_datum);
// Time huidige_tijd = new Time(Calendar.getInstance().getTime().getTime());
System.out.println(huidige_tijd);
PreparedStatement p3 = conn.prepareStatement("INSERT INTO"
+ " historie (datum, aankomst_tijd, persoonsid)"
+ " VALUES (?, ?, (SELECT p.persoonsid"
+ " FROM persoon p, sleutel s"
+ " WHERE p.sleutelid = s.sleutelid"
+ " AND s.sleutelcode = ?))");
p3.setDate(1, huidige_datum);
p3.setTime(2, huidige_tijd);
p3.setInt(3, code);
p3.executeUpdate();
System.out.println(naam + " staat nu in historie");
}
else if (aanwezig == true) {
//Updaten persoon
PreparedStatement p4 = conn.prepareStatement("UPDATE"
+ " persoon"
+ " SET aanwezig = false"
+ " WHERE persoonsid = ?");
p4.setInt(1, persoonsid);
p4.executeUpdate();
System.out.println(persoonsid + " " + naam + " staat nu op afwezig.");
System.out.println();
//updaten historie:
System.out.println("Updating historie:");
// Time huidige_vertrek_tijd = new Time(Calendar.getInstance().getTime().getTime());
System.out.println(huidige_tijd);
PreparedStatement p5 = conn.prepareStatement("UPDATE"
+ " historie"
+ " SET vertrek_tijd = ?"
+ " WHERE persoonsid = ?"
+ " AND aankomst_tijd = ?");
p5.setTime(1, huidige_tijd);
p5.setInt(2, persoonsid);
p5.setTime(3, aankomst_tijd);
p5.executeUpdate();
System.out.println(persoonsid + " " + naam +" " + huidige_tijd);
}
}
} else if (Integer.toString(code).length() > 5) {
System.out.println("Ingevoerde code is te groot!");
} else if (Integer.toString(code).length() < 5) {
System.out.println("Ingevoerde code is te klein!");
}
}
// } catch (SQLException s) {
// s.printStackTrace();
// }
}
}
| thebaron2/DeuropenenSluiten | src/App.java | 1,980 | // Time huidige_vertrek_tijd = new Time(Calendar.getInstance().getTime().getTime()); | line_comment | nl |
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Calendar;
import java.util.Scanner;
//import nl.hu.ipass.persistence.BaseDAO;
public class App {
private static final String db_driv = "org.postgresql.Driver";
private static final String db_url = "jdbc:postgresql://localhost:5432/ipass";
private static final String db_user = "postgres";
private static final String db_pass = "Merlijn26";
private static Connection conn;
public static void main( String[] args ) throws SQLException {
try {
Class.forName(db_driv).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e1) {
e1.printStackTrace();
}
conn = DriverManager.getConnection(db_url, db_user, db_pass);
Scanner scanner = new Scanner(System.in);
while (true) {
Time huidige_tijd = new Time(Calendar.getInstance().getTime().getTime());
System.out.println("Voer uw sleutelcode in: ");
int code = scanner.nextInt();
String stringcode = Integer.toString(code);
if (stringcode.length() == 5) {
System.out.println("Ingevoerde sleutel: " + code);
System.out.println("Checking database...");
PreparedStatement p = conn.prepareStatement("SELECT "
+ "p.persoonsid, p.voornaam, p.achternaam, p.aanwezig "
+ "FROM persoon p, sleutel s "
+ "WHERE p.sleutelid = s.sleutelid "
+ "AND s.sleutelcode = ?");
p.setInt(1, code);
ResultSet rs = p.executeQuery();
if (rs.next()) {
// System.out.println("not supposed to be here!");
int persoonsid = rs.getInt("persoonsid");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
boolean aanwezig = rs.getBoolean("aanwezig");
String naam = voornaam + " " + achternaam;
System.out.println("Welkom " + naam);
// System.out.println(aanwezig);
PreparedStatement p6 = conn.prepareStatement("SELECT "
+ "MAX(aankomst_tijd) AS aankomst_tijd "
+ "FROM historie "
+ "WHERE persoonsid = ? "
+ "AND datum = (SELECT MAX(datum) "
+ " FROM historie "
+ " WHERE persoonsid = ?)");
p6.setInt(1, persoonsid);
p6.setInt(2, persoonsid);
ResultSet rs2 = p6.executeQuery();
rs2.next();
Time aankomst_tijd = rs2.getTime("aankomst_tijd");
System.out.println(aankomst_tijd);
//Select persoonsid:
System.out.println("Updating table persoon...");
if (aanwezig == false) {
//Update persoon where persoonsid = persoonsid hierboven
PreparedStatement p2 = conn.prepareStatement("UPDATE"
+ " persoon"
+ " SET aanwezig = true"
+ " WHERE persoonsid = ?");
p2.setInt(1, persoonsid);
p2.executeUpdate();
System.out.println(persoonsid + " " + naam + " staat nu op aanwezig");
System.out.println();
//inserten historie:
System.out.println("Inserting into historie...");
Date huidige_datum = new Date(Calendar.getInstance().getTime().getTime());
System.out.println(huidige_datum);
// Time huidige_tijd = new Time(Calendar.getInstance().getTime().getTime());
System.out.println(huidige_tijd);
PreparedStatement p3 = conn.prepareStatement("INSERT INTO"
+ " historie (datum, aankomst_tijd, persoonsid)"
+ " VALUES (?, ?, (SELECT p.persoonsid"
+ " FROM persoon p, sleutel s"
+ " WHERE p.sleutelid = s.sleutelid"
+ " AND s.sleutelcode = ?))");
p3.setDate(1, huidige_datum);
p3.setTime(2, huidige_tijd);
p3.setInt(3, code);
p3.executeUpdate();
System.out.println(naam + " staat nu in historie");
}
else if (aanwezig == true) {
//Updaten persoon
PreparedStatement p4 = conn.prepareStatement("UPDATE"
+ " persoon"
+ " SET aanwezig = false"
+ " WHERE persoonsid = ?");
p4.setInt(1, persoonsid);
p4.executeUpdate();
System.out.println(persoonsid + " " + naam + " staat nu op afwezig.");
System.out.println();
//updaten historie:
System.out.println("Updating historie:");
// Time huidige_vertrek_tijd<SUF>
System.out.println(huidige_tijd);
PreparedStatement p5 = conn.prepareStatement("UPDATE"
+ " historie"
+ " SET vertrek_tijd = ?"
+ " WHERE persoonsid = ?"
+ " AND aankomst_tijd = ?");
p5.setTime(1, huidige_tijd);
p5.setInt(2, persoonsid);
p5.setTime(3, aankomst_tijd);
p5.executeUpdate();
System.out.println(persoonsid + " " + naam +" " + huidige_tijd);
}
}
} else if (Integer.toString(code).length() > 5) {
System.out.println("Ingevoerde code is te groot!");
} else if (Integer.toString(code).length() < 5) {
System.out.println("Ingevoerde code is te klein!");
}
}
// } catch (SQLException s) {
// s.printStackTrace();
// }
}
}
|
177492_1 | package nl.hu.ipass.persistence;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import nl.hu.ipass.model.Verzoek;
public class VerzoekDAO extends BaseDAO {
public List<Verzoek> findAll() {
List<Verzoek> verzoeken = new ArrayList<Verzoek>();
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek");
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
int verzoekid = rs.getInt("verzoekid");
String naam_bedrijf = rs.getString("naam_bedrijf");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String straat = rs.getString("straat");
String huisnummer = rs.getString("huisnummer");
String woonplaats = rs.getString("woonplaats");
String postcode = rs.getString("postcode");
String email = rs.getString("email");
Date gbdatum = rs.getDate("gbdatum");
String geslacht = rs.getString("geslacht");
String telnummer = rs.getString("telefoonnummer");
// String wachtwoord = rs.getString("wachtwoord");
boolean aanwezig = rs.getBoolean("aanwezig");
Date datum_ontvangen = rs.getDate("datum_ontvangen");
verzoeken.add(new Verzoek(verzoekid, naam_bedrijf,
voornaam, achternaam, straat,
huisnummer, woonplaats, postcode,
email, gbdatum, geslacht, telnummer,
aanwezig, datum_ontvangen));
}
rs.close();
pstat.close();
} catch(SQLException s) {
s.printStackTrace();
}
return verzoeken;
}
public Verzoek findVerzoekById(int id) {
List<Verzoek> verzoeken = new ArrayList<Verzoek>();
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek WHERE verzoekid = '" + id + "'");
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
int verzoekid = rs.getInt("verzoekid");
String naam_bedrijf = rs.getString("naam_bedrijf");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String straat = rs.getString("straat");
String huisnummer = rs.getString("huisnummer");
String woonplaats = rs.getString("woonplaats");
String postcode = rs.getString("postcode");
String email = rs.getString("email");
Date gbdatum = rs.getDate("gbdatum");
String geslacht = rs.getString("geslacht");
String telnummer = rs.getString("telefoonnummer");
// String wachtwoord = rs.getString("wachtwoord");
boolean aanwezig = rs.getBoolean("aanwezig");
Date datum_ontvangen = rs.getDate("datum_ontvangen");
verzoeken.add(new Verzoek(verzoekid, naam_bedrijf,
voornaam, achternaam, straat,
huisnummer, woonplaats, postcode,
email, gbdatum, geslacht, telnummer,
aanwezig, datum_ontvangen));
}
if (verzoeken.size() > 0) {
rs.close();
pstat.close();
return verzoeken.get(0);
}
rs.close();
pstat.close();
} catch (SQLException s) {
s.printStackTrace();
}
return null;
}
public void saveVerzoek(Verzoek verzoek) throws ParseException {
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("INSERT INTO "
+ "verzoek (naam_bedrijf, voornaam, achternaam, "
+ "straat, huisnummer, woonplaats, "
+ "postcode, email, gbdatum, "
+ "geslacht, telefoonnummer, datum_ontvangen) "
+ "VALUES(?,?,?, ?,?,?, ?,?,?, ?,?,?)");
pstat.setString(1, verzoek.getNaam_bedrijf());
pstat.setString(2, verzoek.getVoornaam());
pstat.setString(3, verzoek.getAchternaam());
pstat.setString(4, verzoek.getStraat());
pstat.setString(5, verzoek.getNummer());
pstat.setString(6, verzoek.getWoonplaats());
pstat.setString(7, verzoek.getPostcode());
pstat.setString(8, verzoek.getEmail());
pstat.setDate(9, fromStringToDate(verzoek.getGbdatumS()));
pstat.setString(10, verzoek.getGeslacht());
pstat.setString(11, verzoek.getTelnummer());
// pstat.setString(12, verzoek.getWachtwoord());
pstat.setDate(12, fromStringToDate(verzoek.getDatum_ontvangenS()));
// System.out.println("komt hier");
pstat.executeUpdate();
pstat.close();
} catch (SQLException s) {
s.printStackTrace();
}
}
public void deleteVerzoekById(int verzoekid) {
try (Connection conn = super.getConnection()) {
PreparedStatement p = conn.prepareStatement("DELETE FROM verzoek "
+ " WHERE verzoekid = ?");
p.setInt(1, verzoekid);
p.executeUpdate();
// System.out.println("Verzoek verwijderd!");
p.close();
} catch (SQLException s) {
s.printStackTrace();
}
}
private java.sql.Date fromStringToDate(String s) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date utilDate = sdf.parse(s);
java.sql.Date sqlDate = new Date(utilDate.getTime());
return sqlDate;
}
}
| thebaron2/ipass | src/main/java/nl/hu/ipass/persistence/VerzoekDAO.java | 1,881 | // String wachtwoord = rs.getString("wachtwoord"); | line_comment | nl | package nl.hu.ipass.persistence;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import nl.hu.ipass.model.Verzoek;
public class VerzoekDAO extends BaseDAO {
public List<Verzoek> findAll() {
List<Verzoek> verzoeken = new ArrayList<Verzoek>();
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek");
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
int verzoekid = rs.getInt("verzoekid");
String naam_bedrijf = rs.getString("naam_bedrijf");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String straat = rs.getString("straat");
String huisnummer = rs.getString("huisnummer");
String woonplaats = rs.getString("woonplaats");
String postcode = rs.getString("postcode");
String email = rs.getString("email");
Date gbdatum = rs.getDate("gbdatum");
String geslacht = rs.getString("geslacht");
String telnummer = rs.getString("telefoonnummer");
// String wachtwoord = rs.getString("wachtwoord");
boolean aanwezig = rs.getBoolean("aanwezig");
Date datum_ontvangen = rs.getDate("datum_ontvangen");
verzoeken.add(new Verzoek(verzoekid, naam_bedrijf,
voornaam, achternaam, straat,
huisnummer, woonplaats, postcode,
email, gbdatum, geslacht, telnummer,
aanwezig, datum_ontvangen));
}
rs.close();
pstat.close();
} catch(SQLException s) {
s.printStackTrace();
}
return verzoeken;
}
public Verzoek findVerzoekById(int id) {
List<Verzoek> verzoeken = new ArrayList<Verzoek>();
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek WHERE verzoekid = '" + id + "'");
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
int verzoekid = rs.getInt("verzoekid");
String naam_bedrijf = rs.getString("naam_bedrijf");
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String straat = rs.getString("straat");
String huisnummer = rs.getString("huisnummer");
String woonplaats = rs.getString("woonplaats");
String postcode = rs.getString("postcode");
String email = rs.getString("email");
Date gbdatum = rs.getDate("gbdatum");
String geslacht = rs.getString("geslacht");
String telnummer = rs.getString("telefoonnummer");
// String wachtwoord<SUF>
boolean aanwezig = rs.getBoolean("aanwezig");
Date datum_ontvangen = rs.getDate("datum_ontvangen");
verzoeken.add(new Verzoek(verzoekid, naam_bedrijf,
voornaam, achternaam, straat,
huisnummer, woonplaats, postcode,
email, gbdatum, geslacht, telnummer,
aanwezig, datum_ontvangen));
}
if (verzoeken.size() > 0) {
rs.close();
pstat.close();
return verzoeken.get(0);
}
rs.close();
pstat.close();
} catch (SQLException s) {
s.printStackTrace();
}
return null;
}
public void saveVerzoek(Verzoek verzoek) throws ParseException {
try (Connection conn = super.getConnection()) {
PreparedStatement pstat = conn.prepareStatement("INSERT INTO "
+ "verzoek (naam_bedrijf, voornaam, achternaam, "
+ "straat, huisnummer, woonplaats, "
+ "postcode, email, gbdatum, "
+ "geslacht, telefoonnummer, datum_ontvangen) "
+ "VALUES(?,?,?, ?,?,?, ?,?,?, ?,?,?)");
pstat.setString(1, verzoek.getNaam_bedrijf());
pstat.setString(2, verzoek.getVoornaam());
pstat.setString(3, verzoek.getAchternaam());
pstat.setString(4, verzoek.getStraat());
pstat.setString(5, verzoek.getNummer());
pstat.setString(6, verzoek.getWoonplaats());
pstat.setString(7, verzoek.getPostcode());
pstat.setString(8, verzoek.getEmail());
pstat.setDate(9, fromStringToDate(verzoek.getGbdatumS()));
pstat.setString(10, verzoek.getGeslacht());
pstat.setString(11, verzoek.getTelnummer());
// pstat.setString(12, verzoek.getWachtwoord());
pstat.setDate(12, fromStringToDate(verzoek.getDatum_ontvangenS()));
// System.out.println("komt hier");
pstat.executeUpdate();
pstat.close();
} catch (SQLException s) {
s.printStackTrace();
}
}
public void deleteVerzoekById(int verzoekid) {
try (Connection conn = super.getConnection()) {
PreparedStatement p = conn.prepareStatement("DELETE FROM verzoek "
+ " WHERE verzoekid = ?");
p.setInt(1, verzoekid);
p.executeUpdate();
// System.out.println("Verzoek verwijderd!");
p.close();
} catch (SQLException s) {
s.printStackTrace();
}
}
private java.sql.Date fromStringToDate(String s) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date utilDate = sdf.parse(s);
java.sql.Date sqlDate = new Date(utilDate.getTime());
return sqlDate;
}
}
|
194829_18 | /*
* OffenePflege
* Copyright (C) 2006-2012 Torsten Löhr
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License V2 as published by the Free Software Foundation
*
* 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 General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if not, write to
* the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
* www.offene-pflege.de
* ------------------------
* Auf deutsch (freie Übersetzung. Rechtlich gilt die englische Version)
* Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License,
* wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, gemäß Version 2 der Lizenz.
*
* Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber
* OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN
* BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License.
*
* Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht,
* schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA.
*
*/
package op.care.info;
import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;
import com.jidesoft.popup.JidePopup;
import entity.EntityTools;
import entity.info.ICD;
import entity.info.ResInfo;
import entity.info.ResInfoTools;
import entity.prescription.GP;
import entity.prescription.GPTools;
import entity.prescription.Hospital;
import entity.prescription.HospitalTools;
import gui.GUITools;
import op.OPDE;
import op.residents.PnlEditGP;
import op.residents.PnlEditHospital;
import op.threads.DisplayMessage;
import op.tools.MyJDialog;
import op.tools.SYSConst;
import op.tools.SYSTools;
import org.apache.commons.collections.Closure;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.JXSearchField;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.*;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Properties;
/**
* @author root
*/
public class DlgDiag extends MyJDialog {
public static final String internalClassID = "nursingrecords.info.dlg.diags";
private ListSelectionListener lsl;
private String text;
private ResInfo diag;
private Closure actionBlock;
/**
* Creates new form DlgVorlage
*/
public DlgDiag(ResInfo diag, Closure actionBlock) {
super(false);
this.diag = diag;
this.actionBlock = actionBlock;
initComponents();
initDialog();
// setVisible(true);
}
private void initDialog() {
fillCMBs();
String tooltip = SYSTools.xx("nursingrecords.info.dlg.diags.tx.tooltip").replace('[', '<').replace(']', '>');
lblTX.setToolTipText(SYSTools.toHTMLForScreen("<p style=\"width:300px;\">" + tooltip + "</p>"));
txtSuche.setPrompt(SYSTools.xx("misc.msg.search"));
lblDiagBy.setText(SYSTools.xx("nursingrecords.info.dlg.diags.by"));
lblSide.setText(SYSTools.xx("misc.msg.diag.side"));
lblSecurity.setText(SYSTools.xx("misc.msg.diag.security"));
lblInterval.setText(SYSTools.xx("nursingrecords.info.dlg.interval_noconstraints"));
lblInterval.setIcon(SYSConst.icon22intervalNoConstraints);
reloadTable();
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags"), 10));
}
private void txtSucheActionPerformed(ActionEvent e) {
reloadTable();
}
private void btnAddGPActionPerformed(ActionEvent e) {
final PnlEditGP pnlGP = new PnlEditGP(new GP());
JidePopup popup = GUITools.createPanelPopup(pnlGP, o -> {
if (o != null) {
GP gp = EntityTools.merge((GP) o);
cmbArzt.setModel(new DefaultComboBoxModel(new GP[]{gp}));
}
}, btnAddGP);
GUITools.showPopup(popup, SwingConstants.EAST);
}
private void btnAddHospitalActionPerformed(ActionEvent e) {
final PnlEditHospital pnlHospital = new PnlEditHospital(new Hospital());
JidePopup popup = GUITools.createPanelPopup(pnlHospital, o -> {
if (o != null) {
Hospital hospital = EntityTools.merge((Hospital) o);
cmbKH.setModel(new DefaultComboBoxModel(new Hospital[]{hospital}));
}
}, btnAddHospital);
GUITools.showPopup(popup, SwingConstants.EAST);
}
private void fillCMBs() {
EntityManager em = OPDE.createEM();
Query queryArzt = em.createQuery("SELECT a FROM GP a WHERE a.status >= 0 ORDER BY a.name, a.vorname");
java.util.List<GP> listAerzte = queryArzt.getResultList();
listAerzte.add(0, null);
Query queryKH = em.createQuery("SELECT k FROM Hospital k WHERE k.state >= 0 ORDER BY k.name");
java.util.List<Hospital> listKH = queryKH.getResultList();
listKH.add(0, null);
em.close();
cmbArzt.setModel(new DefaultComboBoxModel(listAerzte.toArray()));
cmbArzt.setRenderer(GPTools.getRenderer());
cmbArzt.setSelectedIndex(0);
cmbKH.setModel(new DefaultComboBoxModel(listKH.toArray()));
cmbKH.setRenderer(HospitalTools.getKHRenderer());
cmbKH.setSelectedIndex(0);
cmbSicherheit.setModel(new DefaultComboBoxModel(new String[]{
SYSTools.xx("misc.msg.diag.security.na"),
SYSTools.xx("misc.msg.diag.security.confirmed"),
SYSTools.xx("misc.msg.diag.security.suspected"),
SYSTools.xx("misc.msg.diag.security.rulingout"),
SYSTools.xx("misc.msg.diag.security.conditionafter")
}));
cmbSicherheit.setSelectedIndex(1);
cmbKoerper.setModel(new DefaultComboBoxModel(new String[]{
SYSTools.xx("misc.msg.diag.side.na"),
SYSTools.xx("misc.msg.diag.side.left"),
SYSTools.xx("misc.msg.diag.side.right"),
SYSTools.xx("misc.msg.diag.side.both")
}));
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the PrinterForm Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new JPanel();
txtSuche = new JXSearchField();
lblTX = new JLabel();
jspDiagnosen = new JScrollPane();
lstDiag = new JList();
lblDiagBy = new JLabel();
cmbArzt = new JComboBox<>();
btnAddGP = new JButton();
cmbKH = new JComboBox<>();
btnAddHospital = new JButton();
lblSecurity = new JLabel();
lblSide = new JLabel();
cmbKoerper = new JComboBox<>();
cmbSicherheit = new JComboBox<>();
jScrollPane1 = new JScrollPane();
txtBemerkung = new JTextArea();
lblInterval = new JLabel();
panel1 = new JPanel();
btnCancel = new JButton();
btnOK = new JButton();
//======== this ========
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== jPanel1 ========
{
jPanel1.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
jPanel1.setLayout(new FormLayout(
"default, $lcgap, pref, $lcgap, default:grow, $ugap, pref, $lcgap, default:grow, 2*($lcgap, default)",
"default, $lgap, fill:default, $lgap, fill:104dlu:grow, $lgap, fill:default, $lgap, default, $lgap, fill:default, $lgap, fill:89dlu:grow, $ugap, default, $lgap, default"));
//---- txtSuche ----
txtSuche.setFont(new Font("Arial", Font.PLAIN, 14));
txtSuche.addActionListener(e -> txtSucheActionPerformed(e));
jPanel1.add(txtSuche, CC.xywh(3, 3, 7, 1));
//---- lblTX ----
lblTX.setText(null);
lblTX.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/ambulance2.png")));
jPanel1.add(lblTX, CC.xy(11, 3));
//======== jspDiagnosen ========
{
//---- lstDiag ----
lstDiag.setFont(new Font("Arial", Font.PLAIN, 14));
jspDiagnosen.setViewportView(lstDiag);
}
jPanel1.add(jspDiagnosen, CC.xywh(3, 5, 9, 1));
//---- lblDiagBy ----
lblDiagBy.setText("Festgestellt durch:");
lblDiagBy.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblDiagBy, CC.xy(3, 7, CC.RIGHT, CC.DEFAULT));
//---- cmbArzt ----
cmbArzt.setModel(new DefaultComboBoxModel<>(new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
}));
cmbArzt.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbArzt, CC.xywh(5, 7, 5, 1));
//---- btnAddGP ----
btnAddGP.setText(null);
btnAddGP.setBorder(null);
btnAddGP.setContentAreaFilled(false);
btnAddGP.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")));
btnAddGP.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAddGP.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png")));
btnAddGP.addActionListener(e -> btnAddGPActionPerformed(e));
jPanel1.add(btnAddGP, CC.xy(11, 7));
//---- cmbKH ----
cmbKH.setModel(new DefaultComboBoxModel<>(new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
}));
cmbKH.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbKH, CC.xywh(5, 9, 5, 1));
//---- btnAddHospital ----
btnAddHospital.setText(null);
btnAddHospital.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")));
btnAddHospital.setBorder(null);
btnAddHospital.setContentAreaFilled(false);
btnAddHospital.setBorderPainted(false);
btnAddHospital.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAddHospital.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png")));
btnAddHospital.addActionListener(e -> btnAddHospitalActionPerformed(e));
jPanel1.add(btnAddHospital, CC.xy(11, 9));
//---- lblSecurity ----
lblSecurity.setText("Diagnosesicherheit:");
lblSecurity.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblSecurity, CC.xy(7, 11));
//---- lblSide ----
lblSide.setText("K\u00f6rperseite:");
lblSide.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblSide, CC.xy(3, 11, CC.RIGHT, CC.DEFAULT));
//---- cmbKoerper ----
cmbKoerper.setModel(new DefaultComboBoxModel<>(new String[]{
"Nicht festgelegt",
"links",
"rechts",
"beidseitig"
}));
cmbKoerper.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbKoerper, CC.xy(5, 11));
//---- cmbSicherheit ----
cmbSicherheit.setModel(new DefaultComboBoxModel<>(new String[]{
"Nicht festgelegt",
"gesichert",
"Verdacht auf",
"Ausschlu\u00df von",
"Zustand nach"
}));
cmbSicherheit.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbSicherheit, CC.xywh(9, 11, 3, 1));
//======== jScrollPane1 ========
{
//---- txtBemerkung ----
txtBemerkung.setColumns(20);
txtBemerkung.setRows(5);
txtBemerkung.setFont(new Font("Arial", Font.PLAIN, 14));
jScrollPane1.setViewportView(txtBemerkung);
}
jPanel1.add(jScrollPane1, CC.xywh(3, 13, 9, 1));
//---- lblInterval ----
lblInterval.setText("text");
jPanel1.add(lblInterval, CC.xywh(3, 15, 5, 1));
//======== panel1 ========
{
panel1.setLayout(new HorizontalLayout(5));
//---- btnCancel ----
btnCancel.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/cancel.png")));
btnCancel.setText(null);
btnCancel.addActionListener(e -> btnCancelActionPerformed(e));
panel1.add(btnCancel);
//---- btnOK ----
btnOK.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/apply.png")));
btnOK.setText(null);
btnOK.addActionListener(e -> btnOKActionPerformed(e));
panel1.add(btnOK);
}
jPanel1.add(panel1, CC.xywh(7, 15, 5, 1, CC.RIGHT, CC.DEFAULT));
}
contentPane.add(jPanel1, BorderLayout.CENTER);
setSize(730, 565);
setLocationRelativeTo(getOwner());
}// </editor-fold>//GEN-END:initComponents
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
if (saveOK()) {
save();
dispose();
}
}//GEN-LAST:event_btnOKActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
diag = null;
dispose();
}//GEN-LAST:event_btnCancelActionPerformed
@Override
public void dispose() {
super.dispose();
actionBlock.execute(diag);
}
private boolean saveOK() {
boolean saveOK = true;
if (cmbArzt.getSelectedItem() == null && cmbKH.getSelectedItem() == null) {
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.gpANDhospitalempty")));
saveOK = false;
}
if (lstDiag.getSelectedValue() == null) {
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags.emptydiag")));
saveOK = false;
}
return saveOK;
}
private void save() {
GP doc = (GP) cmbArzt.getSelectedItem();
Hospital kh = (Hospital) cmbKH.getSelectedItem();
ICD icd = (ICD) lstDiag.getSelectedValue();
Properties props = new Properties();
props.put("icd", icd.getICD10());
props.put("text", icd.getText());
props.put("koerperseite", cmbKoerper.getSelectedItem());
props.put("diagnosesicherheit", cmbSicherheit.getSelectedItem());
props.put("arztid", doc == null ? "null" : doc.getArztID().toString());
props.put("khid", kh == null ? "null" : kh.getKhid().toString());
String html = "";
html += "<br/>" + SYSConst.html_bold(icd.getICD10() + ": " + icd.getText()) + "<br/>";
html += SYSTools.xx("nursingrecords.info.dlg.diags.by") + ": ";
if (kh != null) {
html += SYSConst.html_bold(HospitalTools.getFullName(kh));
}
if (doc != null) {
if (kh != null) {
html += "<br/>" + SYSTools.xx("misc.msg.confirmedby") + ": ";
}
html += SYSConst.html_bold(GPTools.getFullName(doc)) + "<br/>";
}
html += SYSTools.xx("misc.msg.diag.side") + ": " + SYSConst.html_bold(cmbKoerper.getSelectedItem().toString()) + "<br/>";
html += SYSTools.xx("misc.msg.diag.security") + ": " + SYSConst.html_bold(cmbSicherheit.getSelectedItem().toString()) + "<br/>";
ResInfoTools.setContent(diag, props);
diag.setHtml(html);
diag.setText(txtBemerkung.getText().trim());
}
private void reloadTable() {
if (txtSuche.getText().isEmpty()) {
lstDiag.setModel(new DefaultListModel());
return;
}
EntityManager em = OPDE.createEM();
Query query = em.createQuery("SELECT i FROM ICD i WHERE i.icd10 LIKE :icd10 OR i.text like :text ORDER BY i.icd10 ");
String suche = "%" + txtSuche.getText() + "%";
query.setParameter("icd10", suche);
query.setParameter("text", suche);
lstDiag.setModel(SYSTools.list2dlm(query.getResultList()));
em.close();
lstDiag.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private JPanel jPanel1;
private JXSearchField txtSuche;
private JLabel lblTX;
private JScrollPane jspDiagnosen;
private JList lstDiag;
private JLabel lblDiagBy;
private JComboBox<String> cmbArzt;
private JButton btnAddGP;
private JComboBox<String> cmbKH;
private JButton btnAddHospital;
private JLabel lblSecurity;
private JLabel lblSide;
private JComboBox<String> cmbKoerper;
private JComboBox<String> cmbSicherheit;
private JScrollPane jScrollPane1;
private JTextArea txtBemerkung;
private JLabel lblInterval;
private JPanel panel1;
private JButton btnCancel;
private JButton btnOK;
// End of variables declaration//GEN-END:variables
}
| thebpc/Offene-Pflege.de | src/op/care/info/DlgDiag.java | 5,895 | //---- cmbKoerper ---- | line_comment | nl | /*
* OffenePflege
* Copyright (C) 2006-2012 Torsten Löhr
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License V2 as published by the Free Software Foundation
*
* 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 General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if not, write to
* the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
* www.offene-pflege.de
* ------------------------
* Auf deutsch (freie Übersetzung. Rechtlich gilt die englische Version)
* Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License,
* wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, gemäß Version 2 der Lizenz.
*
* Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber
* OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN
* BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License.
*
* Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht,
* schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA.
*
*/
package op.care.info;
import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;
import com.jidesoft.popup.JidePopup;
import entity.EntityTools;
import entity.info.ICD;
import entity.info.ResInfo;
import entity.info.ResInfoTools;
import entity.prescription.GP;
import entity.prescription.GPTools;
import entity.prescription.Hospital;
import entity.prescription.HospitalTools;
import gui.GUITools;
import op.OPDE;
import op.residents.PnlEditGP;
import op.residents.PnlEditHospital;
import op.threads.DisplayMessage;
import op.tools.MyJDialog;
import op.tools.SYSConst;
import op.tools.SYSTools;
import org.apache.commons.collections.Closure;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.JXSearchField;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.*;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Properties;
/**
* @author root
*/
public class DlgDiag extends MyJDialog {
public static final String internalClassID = "nursingrecords.info.dlg.diags";
private ListSelectionListener lsl;
private String text;
private ResInfo diag;
private Closure actionBlock;
/**
* Creates new form DlgVorlage
*/
public DlgDiag(ResInfo diag, Closure actionBlock) {
super(false);
this.diag = diag;
this.actionBlock = actionBlock;
initComponents();
initDialog();
// setVisible(true);
}
private void initDialog() {
fillCMBs();
String tooltip = SYSTools.xx("nursingrecords.info.dlg.diags.tx.tooltip").replace('[', '<').replace(']', '>');
lblTX.setToolTipText(SYSTools.toHTMLForScreen("<p style=\"width:300px;\">" + tooltip + "</p>"));
txtSuche.setPrompt(SYSTools.xx("misc.msg.search"));
lblDiagBy.setText(SYSTools.xx("nursingrecords.info.dlg.diags.by"));
lblSide.setText(SYSTools.xx("misc.msg.diag.side"));
lblSecurity.setText(SYSTools.xx("misc.msg.diag.security"));
lblInterval.setText(SYSTools.xx("nursingrecords.info.dlg.interval_noconstraints"));
lblInterval.setIcon(SYSConst.icon22intervalNoConstraints);
reloadTable();
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags"), 10));
}
private void txtSucheActionPerformed(ActionEvent e) {
reloadTable();
}
private void btnAddGPActionPerformed(ActionEvent e) {
final PnlEditGP pnlGP = new PnlEditGP(new GP());
JidePopup popup = GUITools.createPanelPopup(pnlGP, o -> {
if (o != null) {
GP gp = EntityTools.merge((GP) o);
cmbArzt.setModel(new DefaultComboBoxModel(new GP[]{gp}));
}
}, btnAddGP);
GUITools.showPopup(popup, SwingConstants.EAST);
}
private void btnAddHospitalActionPerformed(ActionEvent e) {
final PnlEditHospital pnlHospital = new PnlEditHospital(new Hospital());
JidePopup popup = GUITools.createPanelPopup(pnlHospital, o -> {
if (o != null) {
Hospital hospital = EntityTools.merge((Hospital) o);
cmbKH.setModel(new DefaultComboBoxModel(new Hospital[]{hospital}));
}
}, btnAddHospital);
GUITools.showPopup(popup, SwingConstants.EAST);
}
private void fillCMBs() {
EntityManager em = OPDE.createEM();
Query queryArzt = em.createQuery("SELECT a FROM GP a WHERE a.status >= 0 ORDER BY a.name, a.vorname");
java.util.List<GP> listAerzte = queryArzt.getResultList();
listAerzte.add(0, null);
Query queryKH = em.createQuery("SELECT k FROM Hospital k WHERE k.state >= 0 ORDER BY k.name");
java.util.List<Hospital> listKH = queryKH.getResultList();
listKH.add(0, null);
em.close();
cmbArzt.setModel(new DefaultComboBoxModel(listAerzte.toArray()));
cmbArzt.setRenderer(GPTools.getRenderer());
cmbArzt.setSelectedIndex(0);
cmbKH.setModel(new DefaultComboBoxModel(listKH.toArray()));
cmbKH.setRenderer(HospitalTools.getKHRenderer());
cmbKH.setSelectedIndex(0);
cmbSicherheit.setModel(new DefaultComboBoxModel(new String[]{
SYSTools.xx("misc.msg.diag.security.na"),
SYSTools.xx("misc.msg.diag.security.confirmed"),
SYSTools.xx("misc.msg.diag.security.suspected"),
SYSTools.xx("misc.msg.diag.security.rulingout"),
SYSTools.xx("misc.msg.diag.security.conditionafter")
}));
cmbSicherheit.setSelectedIndex(1);
cmbKoerper.setModel(new DefaultComboBoxModel(new String[]{
SYSTools.xx("misc.msg.diag.side.na"),
SYSTools.xx("misc.msg.diag.side.left"),
SYSTools.xx("misc.msg.diag.side.right"),
SYSTools.xx("misc.msg.diag.side.both")
}));
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the PrinterForm Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new JPanel();
txtSuche = new JXSearchField();
lblTX = new JLabel();
jspDiagnosen = new JScrollPane();
lstDiag = new JList();
lblDiagBy = new JLabel();
cmbArzt = new JComboBox<>();
btnAddGP = new JButton();
cmbKH = new JComboBox<>();
btnAddHospital = new JButton();
lblSecurity = new JLabel();
lblSide = new JLabel();
cmbKoerper = new JComboBox<>();
cmbSicherheit = new JComboBox<>();
jScrollPane1 = new JScrollPane();
txtBemerkung = new JTextArea();
lblInterval = new JLabel();
panel1 = new JPanel();
btnCancel = new JButton();
btnOK = new JButton();
//======== this ========
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== jPanel1 ========
{
jPanel1.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
jPanel1.setLayout(new FormLayout(
"default, $lcgap, pref, $lcgap, default:grow, $ugap, pref, $lcgap, default:grow, 2*($lcgap, default)",
"default, $lgap, fill:default, $lgap, fill:104dlu:grow, $lgap, fill:default, $lgap, default, $lgap, fill:default, $lgap, fill:89dlu:grow, $ugap, default, $lgap, default"));
//---- txtSuche ----
txtSuche.setFont(new Font("Arial", Font.PLAIN, 14));
txtSuche.addActionListener(e -> txtSucheActionPerformed(e));
jPanel1.add(txtSuche, CC.xywh(3, 3, 7, 1));
//---- lblTX ----
lblTX.setText(null);
lblTX.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/ambulance2.png")));
jPanel1.add(lblTX, CC.xy(11, 3));
//======== jspDiagnosen ========
{
//---- lstDiag ----
lstDiag.setFont(new Font("Arial", Font.PLAIN, 14));
jspDiagnosen.setViewportView(lstDiag);
}
jPanel1.add(jspDiagnosen, CC.xywh(3, 5, 9, 1));
//---- lblDiagBy ----
lblDiagBy.setText("Festgestellt durch:");
lblDiagBy.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblDiagBy, CC.xy(3, 7, CC.RIGHT, CC.DEFAULT));
//---- cmbArzt ----
cmbArzt.setModel(new DefaultComboBoxModel<>(new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
}));
cmbArzt.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbArzt, CC.xywh(5, 7, 5, 1));
//---- btnAddGP ----
btnAddGP.setText(null);
btnAddGP.setBorder(null);
btnAddGP.setContentAreaFilled(false);
btnAddGP.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")));
btnAddGP.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAddGP.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png")));
btnAddGP.addActionListener(e -> btnAddGPActionPerformed(e));
jPanel1.add(btnAddGP, CC.xy(11, 7));
//---- cmbKH ----
cmbKH.setModel(new DefaultComboBoxModel<>(new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
}));
cmbKH.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbKH, CC.xywh(5, 9, 5, 1));
//---- btnAddHospital ----
btnAddHospital.setText(null);
btnAddHospital.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")));
btnAddHospital.setBorder(null);
btnAddHospital.setContentAreaFilled(false);
btnAddHospital.setBorderPainted(false);
btnAddHospital.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAddHospital.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png")));
btnAddHospital.addActionListener(e -> btnAddHospitalActionPerformed(e));
jPanel1.add(btnAddHospital, CC.xy(11, 9));
//---- lblSecurity ----
lblSecurity.setText("Diagnosesicherheit:");
lblSecurity.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblSecurity, CC.xy(7, 11));
//---- lblSide ----
lblSide.setText("K\u00f6rperseite:");
lblSide.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(lblSide, CC.xy(3, 11, CC.RIGHT, CC.DEFAULT));
//---- cmbKoerper<SUF>
cmbKoerper.setModel(new DefaultComboBoxModel<>(new String[]{
"Nicht festgelegt",
"links",
"rechts",
"beidseitig"
}));
cmbKoerper.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbKoerper, CC.xy(5, 11));
//---- cmbSicherheit ----
cmbSicherheit.setModel(new DefaultComboBoxModel<>(new String[]{
"Nicht festgelegt",
"gesichert",
"Verdacht auf",
"Ausschlu\u00df von",
"Zustand nach"
}));
cmbSicherheit.setFont(new Font("Arial", Font.PLAIN, 14));
jPanel1.add(cmbSicherheit, CC.xywh(9, 11, 3, 1));
//======== jScrollPane1 ========
{
//---- txtBemerkung ----
txtBemerkung.setColumns(20);
txtBemerkung.setRows(5);
txtBemerkung.setFont(new Font("Arial", Font.PLAIN, 14));
jScrollPane1.setViewportView(txtBemerkung);
}
jPanel1.add(jScrollPane1, CC.xywh(3, 13, 9, 1));
//---- lblInterval ----
lblInterval.setText("text");
jPanel1.add(lblInterval, CC.xywh(3, 15, 5, 1));
//======== panel1 ========
{
panel1.setLayout(new HorizontalLayout(5));
//---- btnCancel ----
btnCancel.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/cancel.png")));
btnCancel.setText(null);
btnCancel.addActionListener(e -> btnCancelActionPerformed(e));
panel1.add(btnCancel);
//---- btnOK ----
btnOK.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/apply.png")));
btnOK.setText(null);
btnOK.addActionListener(e -> btnOKActionPerformed(e));
panel1.add(btnOK);
}
jPanel1.add(panel1, CC.xywh(7, 15, 5, 1, CC.RIGHT, CC.DEFAULT));
}
contentPane.add(jPanel1, BorderLayout.CENTER);
setSize(730, 565);
setLocationRelativeTo(getOwner());
}// </editor-fold>//GEN-END:initComponents
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
if (saveOK()) {
save();
dispose();
}
}//GEN-LAST:event_btnOKActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
diag = null;
dispose();
}//GEN-LAST:event_btnCancelActionPerformed
@Override
public void dispose() {
super.dispose();
actionBlock.execute(diag);
}
private boolean saveOK() {
boolean saveOK = true;
if (cmbArzt.getSelectedItem() == null && cmbKH.getSelectedItem() == null) {
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.gpANDhospitalempty")));
saveOK = false;
}
if (lstDiag.getSelectedValue() == null) {
OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags.emptydiag")));
saveOK = false;
}
return saveOK;
}
private void save() {
GP doc = (GP) cmbArzt.getSelectedItem();
Hospital kh = (Hospital) cmbKH.getSelectedItem();
ICD icd = (ICD) lstDiag.getSelectedValue();
Properties props = new Properties();
props.put("icd", icd.getICD10());
props.put("text", icd.getText());
props.put("koerperseite", cmbKoerper.getSelectedItem());
props.put("diagnosesicherheit", cmbSicherheit.getSelectedItem());
props.put("arztid", doc == null ? "null" : doc.getArztID().toString());
props.put("khid", kh == null ? "null" : kh.getKhid().toString());
String html = "";
html += "<br/>" + SYSConst.html_bold(icd.getICD10() + ": " + icd.getText()) + "<br/>";
html += SYSTools.xx("nursingrecords.info.dlg.diags.by") + ": ";
if (kh != null) {
html += SYSConst.html_bold(HospitalTools.getFullName(kh));
}
if (doc != null) {
if (kh != null) {
html += "<br/>" + SYSTools.xx("misc.msg.confirmedby") + ": ";
}
html += SYSConst.html_bold(GPTools.getFullName(doc)) + "<br/>";
}
html += SYSTools.xx("misc.msg.diag.side") + ": " + SYSConst.html_bold(cmbKoerper.getSelectedItem().toString()) + "<br/>";
html += SYSTools.xx("misc.msg.diag.security") + ": " + SYSConst.html_bold(cmbSicherheit.getSelectedItem().toString()) + "<br/>";
ResInfoTools.setContent(diag, props);
diag.setHtml(html);
diag.setText(txtBemerkung.getText().trim());
}
private void reloadTable() {
if (txtSuche.getText().isEmpty()) {
lstDiag.setModel(new DefaultListModel());
return;
}
EntityManager em = OPDE.createEM();
Query query = em.createQuery("SELECT i FROM ICD i WHERE i.icd10 LIKE :icd10 OR i.text like :text ORDER BY i.icd10 ");
String suche = "%" + txtSuche.getText() + "%";
query.setParameter("icd10", suche);
query.setParameter("text", suche);
lstDiag.setModel(SYSTools.list2dlm(query.getResultList()));
em.close();
lstDiag.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private JPanel jPanel1;
private JXSearchField txtSuche;
private JLabel lblTX;
private JScrollPane jspDiagnosen;
private JList lstDiag;
private JLabel lblDiagBy;
private JComboBox<String> cmbArzt;
private JButton btnAddGP;
private JComboBox<String> cmbKH;
private JButton btnAddHospital;
private JLabel lblSecurity;
private JLabel lblSide;
private JComboBox<String> cmbKoerper;
private JComboBox<String> cmbSicherheit;
private JScrollPane jScrollPane1;
private JTextArea txtBemerkung;
private JLabel lblInterval;
private JPanel panel1;
private JButton btnCancel;
private JButton btnOK;
// End of variables declaration//GEN-END:variables
}
|
67196_10 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.search.annotations.Field;
/**
* In OpenMRS, we distinguish between data and metadata within our data model. Metadata represent
* system and descriptive data such as data types — a relationship type or encounter type.
* Metadata are generally referenced by clinical data but don't represent patient-specific data
* themselves. This provides a default abstract implementation of the OpenmrsMetadata interface
*
* @since 1.5
* @see OpenmrsMetadata
*/
@MappedSuperclass
public abstract class BaseOpenmrsMetadata extends BaseOpenmrsObject implements OpenmrsMetadata {
//***** Properties *****
@Column(name = "name", nullable = false, length = 255)
@Field
private String name;
@Column(name = "description", length = 255)
private String description;
@ManyToOne(optional = false)
@JoinColumn(name = "creator")
private User creator;
@Column(name = "date_created", nullable = false)
private Date dateCreated;
@ManyToOne
@JoinColumn(name = "changed_by")
private User changedBy;
@Column(name = "date_changed")
private Date dateChanged;
@Column(name = "retired", nullable = false)
@Field
private Boolean retired = Boolean.FALSE;
@Column(name = "date_retired")
private Date dateRetired;
@ManyToOne
@JoinColumn(name = "retired_by")
private User retiredBy;
@Column(name = "retire_reason", length = 255)
private String retireReason;
//***** Constructors *****
/**
* Default Constructor
*/
public BaseOpenmrsMetadata() {
}
//***** Property Access *****
/**
* @return the name
*/
@Override
public String getName() {
return name;
}
/**
* @param name the name to set
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* @return the description
*/
@Override
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
@Override
public void setDescription(String description) {
this.description = description;
}
/**
* @see org.openmrs.OpenmrsMetadata#getCreator()
*/
@Override
public User getCreator() {
return creator;
}
/**
* @see org.openmrs.OpenmrsMetadata#setCreator(org.openmrs.User)
*/
@Override
public void setCreator(User creator) {
this.creator = creator;
}
/**
* @see org.openmrs.OpenmrsMetadata#getDateCreated()
*/
@Override
public Date getDateCreated() {
return dateCreated;
}
/**
* @see org.openmrs.OpenmrsMetadata#setDateCreated(java.util.Date)
*/
@Override
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* @see org.openmrs.OpenmrsMetadata#getChangedBy()
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public User getChangedBy() {
return changedBy;
}
/**
* @see org.openmrs.OpenmrsMetadata#setChangedBy(User)
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public void setChangedBy(User changedBy) {
this.changedBy = changedBy;
}
/**
* @see org.openmrs.OpenmrsMetadata#getDateChanged()
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public Date getDateChanged() {
return dateChanged;
}
/**
* @see org.openmrs.OpenmrsMetadata#setDateChanged(Date)
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public void setDateChanged(Date dateChanged) {
this.dateChanged = dateChanged;
}
/**
* @deprecated as of 2.0, use {@link #getRetired()}
* @see org.openmrs.Retireable#isRetired()
*/
@Override
@Deprecated
@JsonIgnore
public Boolean isRetired() {
return getRetired();
}
/**
* This method delegates to {@link #isRetired()}. This is only needed for jstl syntax like
* ${fieldType.retired} because the return type is a Boolean object instead of a boolean
* primitive type.
*
* @see org.openmrs.Retireable#isRetired()
*/
@Override
public Boolean getRetired() {
return retired;
}
/**
* @see org.openmrs.Retireable#setRetired(java.lang.Boolean)
*/
@Override
public void setRetired(Boolean retired) {
this.retired = retired;
}
/**
* @see org.openmrs.Retireable#getDateRetired()
*/
@Override
public Date getDateRetired() {
return dateRetired;
}
/**
* @see org.openmrs.Retireable#setDateRetired(java.util.Date)
*/
@Override
public void setDateRetired(Date dateRetired) {
this.dateRetired = dateRetired;
}
/**
* @see org.openmrs.Retireable#getRetiredBy()
*/
@Override
public User getRetiredBy() {
return retiredBy;
}
/**
* @see org.openmrs.Retireable#setRetiredBy(org.openmrs.User)
*/
@Override
public void setRetiredBy(User retiredBy) {
this.retiredBy = retiredBy;
}
/**
* @see org.openmrs.Retireable#getRetireReason()
*/
@Override
public String getRetireReason() {
return retireReason;
}
/**
* @see org.openmrs.Retireable#setRetireReason(java.lang.String)
*/
@Override
public void setRetireReason(String retireReason) {
this.retireReason = retireReason;
}
}
| thegreyd/openmrs-core | api/src/main/java/org/openmrs/BaseOpenmrsMetadata.java | 1,983 | /**
* @see org.openmrs.OpenmrsMetadata#getDateCreated()
*/ | block_comment | nl | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.search.annotations.Field;
/**
* In OpenMRS, we distinguish between data and metadata within our data model. Metadata represent
* system and descriptive data such as data types — a relationship type or encounter type.
* Metadata are generally referenced by clinical data but don't represent patient-specific data
* themselves. This provides a default abstract implementation of the OpenmrsMetadata interface
*
* @since 1.5
* @see OpenmrsMetadata
*/
@MappedSuperclass
public abstract class BaseOpenmrsMetadata extends BaseOpenmrsObject implements OpenmrsMetadata {
//***** Properties *****
@Column(name = "name", nullable = false, length = 255)
@Field
private String name;
@Column(name = "description", length = 255)
private String description;
@ManyToOne(optional = false)
@JoinColumn(name = "creator")
private User creator;
@Column(name = "date_created", nullable = false)
private Date dateCreated;
@ManyToOne
@JoinColumn(name = "changed_by")
private User changedBy;
@Column(name = "date_changed")
private Date dateChanged;
@Column(name = "retired", nullable = false)
@Field
private Boolean retired = Boolean.FALSE;
@Column(name = "date_retired")
private Date dateRetired;
@ManyToOne
@JoinColumn(name = "retired_by")
private User retiredBy;
@Column(name = "retire_reason", length = 255)
private String retireReason;
//***** Constructors *****
/**
* Default Constructor
*/
public BaseOpenmrsMetadata() {
}
//***** Property Access *****
/**
* @return the name
*/
@Override
public String getName() {
return name;
}
/**
* @param name the name to set
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* @return the description
*/
@Override
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
@Override
public void setDescription(String description) {
this.description = description;
}
/**
* @see org.openmrs.OpenmrsMetadata#getCreator()
*/
@Override
public User getCreator() {
return creator;
}
/**
* @see org.openmrs.OpenmrsMetadata#setCreator(org.openmrs.User)
*/
@Override
public void setCreator(User creator) {
this.creator = creator;
}
/**
* @see org.openmrs.OpenmrsMetadata#getDateCreated()
<SUF>*/
@Override
public Date getDateCreated() {
return dateCreated;
}
/**
* @see org.openmrs.OpenmrsMetadata#setDateCreated(java.util.Date)
*/
@Override
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* @see org.openmrs.OpenmrsMetadata#getChangedBy()
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public User getChangedBy() {
return changedBy;
}
/**
* @see org.openmrs.OpenmrsMetadata#setChangedBy(User)
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public void setChangedBy(User changedBy) {
this.changedBy = changedBy;
}
/**
* @see org.openmrs.OpenmrsMetadata#getDateChanged()
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public Date getDateChanged() {
return dateChanged;
}
/**
* @see org.openmrs.OpenmrsMetadata#setDateChanged(Date)
* @deprecated as of version 2.2
*/
@Override
@Deprecated
public void setDateChanged(Date dateChanged) {
this.dateChanged = dateChanged;
}
/**
* @deprecated as of 2.0, use {@link #getRetired()}
* @see org.openmrs.Retireable#isRetired()
*/
@Override
@Deprecated
@JsonIgnore
public Boolean isRetired() {
return getRetired();
}
/**
* This method delegates to {@link #isRetired()}. This is only needed for jstl syntax like
* ${fieldType.retired} because the return type is a Boolean object instead of a boolean
* primitive type.
*
* @see org.openmrs.Retireable#isRetired()
*/
@Override
public Boolean getRetired() {
return retired;
}
/**
* @see org.openmrs.Retireable#setRetired(java.lang.Boolean)
*/
@Override
public void setRetired(Boolean retired) {
this.retired = retired;
}
/**
* @see org.openmrs.Retireable#getDateRetired()
*/
@Override
public Date getDateRetired() {
return dateRetired;
}
/**
* @see org.openmrs.Retireable#setDateRetired(java.util.Date)
*/
@Override
public void setDateRetired(Date dateRetired) {
this.dateRetired = dateRetired;
}
/**
* @see org.openmrs.Retireable#getRetiredBy()
*/
@Override
public User getRetiredBy() {
return retiredBy;
}
/**
* @see org.openmrs.Retireable#setRetiredBy(org.openmrs.User)
*/
@Override
public void setRetiredBy(User retiredBy) {
this.retiredBy = retiredBy;
}
/**
* @see org.openmrs.Retireable#getRetireReason()
*/
@Override
public String getRetireReason() {
return retireReason;
}
/**
* @see org.openmrs.Retireable#setRetireReason(java.lang.String)
*/
@Override
public void setRetireReason(String retireReason) {
this.retireReason = retireReason;
}
}
|
143983_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.hof.se2.managedBean;
import de.hof.se2.eigeneNoten.BerechneteNoten;
import de.hof.se2.eigeneNoten.Endnote;
import de.hof.se2.entity.Noten;
import de.hof.se2.entity.Personen;
import de.hof.se2.logik.Statistik;
import de.hof.se2.sessionBean.BerechnungNotenLocal;
import de.hof.se2.sessionBean.StatistikBeanLocal;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.w3c.dom.Document;
/**
* Managed Bean mit der die Funktionalität für Studierende erzeugt wird
*
* @author markus
* @version 0.3
* @since 14.12.2015
*/
@Named(value = "outForStudents")
@SessionScoped
public class OutForStudents implements Serializable {
@Default
Document doc;
@LoggedIn
User user;
// @Current Document doc;
// @LoggedIn User user;
@EJB
private BerechnungNotenLocal berechnungNoten;
@EJB
private StatistikBeanLocal statistikBeanLocal;
@PersistenceContext
EntityManager em;
private Personen student;
//private Personen student;
public OutForStudents() {
}
/**
* Creates a new instance of OutForStudents
*
* @param matrikelNr
*/
//public OutForStudents(int matrikelNr) {
// student = em.createNamedQuery("Personen.findByIdPersonen", Personen.class).setParameter("idPersonen", matrikelNr).getResultList().get(0);
//}
/**
* Gibt eine Liste der Noten für den jeweiligen Studierenden zurück
*
* @author markus
* @version 0.3
* @since 10.11.2015
* @param matrikelNr
* @return Liste der Noten für den jeweiligen Studenten
* @deprecated Weil auf der JSF Seite nur noch mit einem Personen Objekt
* gearbeitet wird und die Notenliste direkt aus dem Objekt aufgerufen
* werden kann
*/
@Deprecated
@Named
public List<Noten> getAllNotenForStudent(int matrikelNr) {
/* Alte Version ohne Named Query:
List<Noten> liste_noten_student = new ArrayList<Noten>();
liste_noten_student = (List<Noten>) em.createNativeQuery("select * from noten where Matrikelnr = " + matrikelNr, Noten.class).getResultList();
return liste_noten_student;
Neue Version:
*/
Personen person = this.getStudent(matrikelNr);
return person.getNotenList();
}
/**
* Klasse um ein Objekt vom Typ Personen zurück zu liefern um in der Ausgabe
* einige Parameter gleich bei der Hand zu haben
*
* @author markus
* @version 0.1
* @since 09.11.2015
* @param matrikelNr
* @return Objekt vom Typ "Personen" zu der jeweiligen Matrikelnr.
*/
public Personen getStudent(int matrikelNr) {
// Die Personen sind unique, deshalb kann hier ohne Bedenken das erste Element aus der Mange genommen werden, keine schöne Lösung
// aber derzeit die stressfreiste
// To do:
// - andere Lösung suchen
//List<Personen> person = em.createNamedQuery("Personen.findByIdPersonen", Personen.class).setParameter("idPersonen", matrikelNr).getResultList();
student = em.find(Personen.class, matrikelNr); //person.get(0);
return student;
//return person.get(0);
}
/**
* Methode um Änderungen am Objekt "Student" in die DB zu schreiben
*
* @author markus
* @version 0.2
* @param student
* @since 17.12.2015
* @deprecated Derzeit nicht funktionsfähig
*
*/
@Deprecated
@Transactional
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setStudent(Personen student) {
//public void setStudent() {
//em.persist(student);
System.out.println(student.getNotenList().toString());
em.merge(student);
em.flush();
/*em.merge(student);
em.persist(student);
em.flush();*/
}
/**
* Gibt das Arithmetische Mittel eines Studienfaches zurück
*
* @author max
* @param idStudienfach
* @return Arithmetisches Mittel des Studiengangs aus der berechnungNoten
* Bean
*/
@Named
public double getArithmetischesMittel(int idStudienfach) {
return this.berechnungNoten.getArithmethischesMittel(idStudienfach);
}
/**
* Holt Varianz des übergebenen Studienfaches
*
* @author max
* @param idStudienfach
* @return Varianz des Studiengangs aus der berechnungNoten Bean
*/
@Named
public double getVarianz(int idStudienfach) {
return this.berechnungNoten.getVarianz(idStudienfach);
}
/**
* Holt Standardabweichung für das übergebene Studienfach
*
* @author max
* @param idStudienfach
* @return Standardabweichung des Studiengangs aus der berechnungNoten Bean
*/
@Named
public double getStandardabweichung(int idStudienfach) {
return this.berechnungNoten.getStandardabweichung(idStudienfach);
}
/**
* Holt MEdian des Studienfachs ab
*
* @author max
* @param idStudienfach
* @return Median des Studiengangs aus der berechnungNoten Bean
*/
@Named
public int getMedian(int idStudienfach) {
return this.berechnungNoten.getMedian(idStudienfach);
}
/**
* Gibt eine Liste von Statistik Objekte zurueck, die nach Notenart
* unterscheiden
*
* @author Maximilian Schreiber
* @param idStudienfach
* @return List<Statistik>
*/
@Named
public List<Statistik> getStatistik(int idStudienfach) {
return this.statistikBeanLocal.getStatistik(idStudienfach);
}
/**
* Holt Ednote des Studenten ab
*
* @param personId Student
* @return berechnete Endnote des Studenten
*/
@Named
public Endnote getEndnote(int personId) {
return this.berechnungNoten.getEndnote(personId);
}
/**
* Holt die Endnote mit den Wuschnoten des Studenten ab
*
* @param personId Student
* @return Berechnete Endnote mit Wunschnoten
*/
@Named
public double getWunschEndnote(int personId) {
return this.berechnungNoten.getWunschEndnote(personId);
}
/**
* Holt Person aus der Datenbank, die dem Studenten entspricht aus der
* Datenbank
*
* @param personId Studenten ID
* @return Person, die eingeloggt ist
*/
@Named
public Personen getPerson(int personId) {
List<Personen> liste = em.createNativeQuery("select * from personen where idPersonen = " + personId, Personen.class).getResultList();
return liste.get(0);
}
/**
* Erzeugt Statistik für eine Notenliste über die StatistikBean
*
* @param notenListe Notenliste aus der die Statistik erzeugt werden soll
* @return Statistik der Notenliste
* @deprecated
*/
@Named
@Deprecated
public Statistik getStatistik(List<Noten> notenListe) {
return this.statistikBeanLocal.getStatistik(notenListe);
}
// @Named
// @Deprecated
// public Zwischenpruefungsnote getZwischenpruefungsnote(int personID) {
// return this.berechnungNoten.getNoteGrundstudium(personID);
// }
/**
* Holt Note mit Relativer gewichtung zur Endnote
*
* @param note Die Einzelnote, deren gewichtung berechnet werden soll
* @param endnote Endnote
* @return Gewichtung der jeweiligen Note
*/
@Named
public double getRelativeGewichtung(Noten note, Endnote endnote) {
return this.berechnungNoten.getRelativeGewichtung(note, endnote);
}
/**
*
* @param personID
* @return
*/
@Named
public BerechneteNoten getBerechneteNoten(int personID) {
return this.berechnungNoten.getBerechneteNoten(personID);
}
/**
*
* Erzeut eine Notenliste, geordnet nach Semestern der PErson, die abgefragt
* wird
*
* @param personID Student für den die Liste erzeugt werden soll
* @return Notenliste, sortiert nach Semestern für einen Studenten
*/
@Named
public List<Noten> getNotenListSortedSemester(int personID) {
return this.em.createNativeQuery("select n.* from noten n, studienfaecher s where Matrikelnr = " + personID + " and s.idStudienfach = n.studienfach_id order by s.semester", Noten.class).getResultList();
}
/**
* Methode um die Wunschnote in die Datenbank zu schreiben, soll aus der JSF
* Seite mit bspw. onblur aufgerufen werden und eine(!) Note in die
* Datenbank schreiben
*
* @param notenID ID der zu ändernden Note
* @param wunschNote neuer Wert der Wunschnote
* @author markus
* @version 0.1
* @since 15.12.2015
* @todo Native Query umbauen
*/
@Transactional
public void setWunschnote(int notenID, int wunschNote) {
//wunschNote = 5;
//Query update_query_wunschnote = em.createNativeQuery("update noten.noten set Wunschnote=" + wunschNote + " where idNoten=" + notenID);
//int wunschNoteI = Integer.parseInt(wunschNote);
Query update_query_wunschnote = em.createNativeQuery("update noten.noten set Wunschnote= ? where idNoten= ?");
update_query_wunschnote.setParameter(2, notenID);
update_query_wunschnote.setParameter(1, wunschNote);
update_query_wunschnote.executeUpdate();
}
/**
* Methode um die komplette Seite zu speichern
* http://stackoverflow.com/questions/19002570/retrieving-value-of-jsf-input-field-without-managed-bean-property
*
* @version 0.1
* @since 15.12.2015
*/
@Transactional
public void save() {
em.persist(student);
//ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
//ec.getRequestParameterMap().get("");
}
}
| themanwhosold/notenrechner | src/main/java/de/hof/se2/managedBean/OutForStudents.java | 3,354 | //private Personen student; | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.hof.se2.managedBean;
import de.hof.se2.eigeneNoten.BerechneteNoten;
import de.hof.se2.eigeneNoten.Endnote;
import de.hof.se2.entity.Noten;
import de.hof.se2.entity.Personen;
import de.hof.se2.logik.Statistik;
import de.hof.se2.sessionBean.BerechnungNotenLocal;
import de.hof.se2.sessionBean.StatistikBeanLocal;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.w3c.dom.Document;
/**
* Managed Bean mit der die Funktionalität für Studierende erzeugt wird
*
* @author markus
* @version 0.3
* @since 14.12.2015
*/
@Named(value = "outForStudents")
@SessionScoped
public class OutForStudents implements Serializable {
@Default
Document doc;
@LoggedIn
User user;
// @Current Document doc;
// @LoggedIn User user;
@EJB
private BerechnungNotenLocal berechnungNoten;
@EJB
private StatistikBeanLocal statistikBeanLocal;
@PersistenceContext
EntityManager em;
private Personen student;
//private Personen<SUF>
public OutForStudents() {
}
/**
* Creates a new instance of OutForStudents
*
* @param matrikelNr
*/
//public OutForStudents(int matrikelNr) {
// student = em.createNamedQuery("Personen.findByIdPersonen", Personen.class).setParameter("idPersonen", matrikelNr).getResultList().get(0);
//}
/**
* Gibt eine Liste der Noten für den jeweiligen Studierenden zurück
*
* @author markus
* @version 0.3
* @since 10.11.2015
* @param matrikelNr
* @return Liste der Noten für den jeweiligen Studenten
* @deprecated Weil auf der JSF Seite nur noch mit einem Personen Objekt
* gearbeitet wird und die Notenliste direkt aus dem Objekt aufgerufen
* werden kann
*/
@Deprecated
@Named
public List<Noten> getAllNotenForStudent(int matrikelNr) {
/* Alte Version ohne Named Query:
List<Noten> liste_noten_student = new ArrayList<Noten>();
liste_noten_student = (List<Noten>) em.createNativeQuery("select * from noten where Matrikelnr = " + matrikelNr, Noten.class).getResultList();
return liste_noten_student;
Neue Version:
*/
Personen person = this.getStudent(matrikelNr);
return person.getNotenList();
}
/**
* Klasse um ein Objekt vom Typ Personen zurück zu liefern um in der Ausgabe
* einige Parameter gleich bei der Hand zu haben
*
* @author markus
* @version 0.1
* @since 09.11.2015
* @param matrikelNr
* @return Objekt vom Typ "Personen" zu der jeweiligen Matrikelnr.
*/
public Personen getStudent(int matrikelNr) {
// Die Personen sind unique, deshalb kann hier ohne Bedenken das erste Element aus der Mange genommen werden, keine schöne Lösung
// aber derzeit die stressfreiste
// To do:
// - andere Lösung suchen
//List<Personen> person = em.createNamedQuery("Personen.findByIdPersonen", Personen.class).setParameter("idPersonen", matrikelNr).getResultList();
student = em.find(Personen.class, matrikelNr); //person.get(0);
return student;
//return person.get(0);
}
/**
* Methode um Änderungen am Objekt "Student" in die DB zu schreiben
*
* @author markus
* @version 0.2
* @param student
* @since 17.12.2015
* @deprecated Derzeit nicht funktionsfähig
*
*/
@Deprecated
@Transactional
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setStudent(Personen student) {
//public void setStudent() {
//em.persist(student);
System.out.println(student.getNotenList().toString());
em.merge(student);
em.flush();
/*em.merge(student);
em.persist(student);
em.flush();*/
}
/**
* Gibt das Arithmetische Mittel eines Studienfaches zurück
*
* @author max
* @param idStudienfach
* @return Arithmetisches Mittel des Studiengangs aus der berechnungNoten
* Bean
*/
@Named
public double getArithmetischesMittel(int idStudienfach) {
return this.berechnungNoten.getArithmethischesMittel(idStudienfach);
}
/**
* Holt Varianz des übergebenen Studienfaches
*
* @author max
* @param idStudienfach
* @return Varianz des Studiengangs aus der berechnungNoten Bean
*/
@Named
public double getVarianz(int idStudienfach) {
return this.berechnungNoten.getVarianz(idStudienfach);
}
/**
* Holt Standardabweichung für das übergebene Studienfach
*
* @author max
* @param idStudienfach
* @return Standardabweichung des Studiengangs aus der berechnungNoten Bean
*/
@Named
public double getStandardabweichung(int idStudienfach) {
return this.berechnungNoten.getStandardabweichung(idStudienfach);
}
/**
* Holt MEdian des Studienfachs ab
*
* @author max
* @param idStudienfach
* @return Median des Studiengangs aus der berechnungNoten Bean
*/
@Named
public int getMedian(int idStudienfach) {
return this.berechnungNoten.getMedian(idStudienfach);
}
/**
* Gibt eine Liste von Statistik Objekte zurueck, die nach Notenart
* unterscheiden
*
* @author Maximilian Schreiber
* @param idStudienfach
* @return List<Statistik>
*/
@Named
public List<Statistik> getStatistik(int idStudienfach) {
return this.statistikBeanLocal.getStatistik(idStudienfach);
}
/**
* Holt Ednote des Studenten ab
*
* @param personId Student
* @return berechnete Endnote des Studenten
*/
@Named
public Endnote getEndnote(int personId) {
return this.berechnungNoten.getEndnote(personId);
}
/**
* Holt die Endnote mit den Wuschnoten des Studenten ab
*
* @param personId Student
* @return Berechnete Endnote mit Wunschnoten
*/
@Named
public double getWunschEndnote(int personId) {
return this.berechnungNoten.getWunschEndnote(personId);
}
/**
* Holt Person aus der Datenbank, die dem Studenten entspricht aus der
* Datenbank
*
* @param personId Studenten ID
* @return Person, die eingeloggt ist
*/
@Named
public Personen getPerson(int personId) {
List<Personen> liste = em.createNativeQuery("select * from personen where idPersonen = " + personId, Personen.class).getResultList();
return liste.get(0);
}
/**
* Erzeugt Statistik für eine Notenliste über die StatistikBean
*
* @param notenListe Notenliste aus der die Statistik erzeugt werden soll
* @return Statistik der Notenliste
* @deprecated
*/
@Named
@Deprecated
public Statistik getStatistik(List<Noten> notenListe) {
return this.statistikBeanLocal.getStatistik(notenListe);
}
// @Named
// @Deprecated
// public Zwischenpruefungsnote getZwischenpruefungsnote(int personID) {
// return this.berechnungNoten.getNoteGrundstudium(personID);
// }
/**
* Holt Note mit Relativer gewichtung zur Endnote
*
* @param note Die Einzelnote, deren gewichtung berechnet werden soll
* @param endnote Endnote
* @return Gewichtung der jeweiligen Note
*/
@Named
public double getRelativeGewichtung(Noten note, Endnote endnote) {
return this.berechnungNoten.getRelativeGewichtung(note, endnote);
}
/**
*
* @param personID
* @return
*/
@Named
public BerechneteNoten getBerechneteNoten(int personID) {
return this.berechnungNoten.getBerechneteNoten(personID);
}
/**
*
* Erzeut eine Notenliste, geordnet nach Semestern der PErson, die abgefragt
* wird
*
* @param personID Student für den die Liste erzeugt werden soll
* @return Notenliste, sortiert nach Semestern für einen Studenten
*/
@Named
public List<Noten> getNotenListSortedSemester(int personID) {
return this.em.createNativeQuery("select n.* from noten n, studienfaecher s where Matrikelnr = " + personID + " and s.idStudienfach = n.studienfach_id order by s.semester", Noten.class).getResultList();
}
/**
* Methode um die Wunschnote in die Datenbank zu schreiben, soll aus der JSF
* Seite mit bspw. onblur aufgerufen werden und eine(!) Note in die
* Datenbank schreiben
*
* @param notenID ID der zu ändernden Note
* @param wunschNote neuer Wert der Wunschnote
* @author markus
* @version 0.1
* @since 15.12.2015
* @todo Native Query umbauen
*/
@Transactional
public void setWunschnote(int notenID, int wunschNote) {
//wunschNote = 5;
//Query update_query_wunschnote = em.createNativeQuery("update noten.noten set Wunschnote=" + wunschNote + " where idNoten=" + notenID);
//int wunschNoteI = Integer.parseInt(wunschNote);
Query update_query_wunschnote = em.createNativeQuery("update noten.noten set Wunschnote= ? where idNoten= ?");
update_query_wunschnote.setParameter(2, notenID);
update_query_wunschnote.setParameter(1, wunschNote);
update_query_wunschnote.executeUpdate();
}
/**
* Methode um die komplette Seite zu speichern
* http://stackoverflow.com/questions/19002570/retrieving-value-of-jsf-input-field-without-managed-bean-property
*
* @version 0.1
* @since 15.12.2015
*/
@Transactional
public void save() {
em.persist(student);
//ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
//ec.getRequestParameterMap().get("");
}
}
|
114422_19 | /*
* Copyright (C) 2010, Garmin International
* Copyright (C) 2010, Matt Fischer <[email protected]> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.revwalk;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
/**
* Interface for revision walkers that perform depth filtering.
*/
public interface DepthWalk {
/**
* Get depth to filter to.
*
* @return Depth to filter to.
*/
int getDepth();
/**
* @return the deepen-since value; if not 0, this walk only returns commits
* whose commit time is at or after this limit
* @since 5.2
*/
default int getDeepenSince() {
return 0;
}
/**
* @return the objects specified by the client using --shallow-exclude
* @since 5.2
*/
default List<ObjectId> getDeepenNots() {
return Collections.emptyList();
}
/** @return flag marking commits that should become unshallow. */
/**
* Get flag marking commits that should become unshallow.
*
* @return flag marking commits that should become unshallow.
*/
RevFlag getUnshallowFlag();
/**
* Get flag marking commits that are interesting again.
*
* @return flag marking commits that are interesting again.
*/
RevFlag getReinterestingFlag();
/**
* @return flag marking commits that are to be excluded because of --shallow-exclude
* @since 5.2
*/
RevFlag getDeepenNotFlag();
/** RevCommit with a depth (in commits) from a root. */
public static class Commit extends RevCommit {
/** Depth of this commit in the graph, via shortest path. */
int depth;
boolean isBoundary;
/**
* True if this commit was excluded due to a shallow fetch
* setting. All its children are thus boundary commits.
*/
boolean makesChildBoundary;
/** @return depth of this commit, as found by the shortest path. */
public int getDepth() {
return depth;
}
/**
* @return true if at least one of this commit's parents was excluded
* due to a shallow fetch setting, false otherwise
* @since 5.2
*/
public boolean isBoundary() {
return isBoundary;
}
/**
* Initialize a new commit.
*
* @param id
* object name for the commit.
*/
protected Commit(AnyObjectId id) {
super(id);
depth = -1;
}
}
/** Subclass of RevWalk that performs depth filtering. */
public class RevWalk extends org.eclipse.jgit.revwalk.RevWalk implements DepthWalk {
private final int depth;
private int deepenSince;
private List<ObjectId> deepenNots;
private final RevFlag UNSHALLOW;
private final RevFlag REINTERESTING;
private final RevFlag DEEPEN_NOT;
/**
* @param repo Repository to walk
* @param depth Maximum depth to return
*/
public RevWalk(Repository repo, int depth) {
super(repo);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* @param or ObjectReader to use
* @param depth Maximum depth to return
*/
public RevWalk(ObjectReader or, int depth) {
super(or);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* Mark a root commit (i.e., one whose depth should be considered 0.)
*
* @param c
* Commit to mark
* @throws IOException
* @throws IncorrectObjectTypeException
* @throws MissingObjectException
*/
public void markRoot(RevCommit c) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
if (c instanceof Commit)
((Commit) c).depth = 0;
super.markStart(c);
}
@Override
protected RevCommit createCommit(AnyObjectId id) {
return new Commit(id);
}
@Override
public int getDepth() {
return depth;
}
@Override
public int getDeepenSince() {
return deepenSince;
}
/**
* Sets the deepen-since value.
*
* @param limit
* new deepen-since value
* @since 5.2
*/
public void setDeepenSince(int limit) {
deepenSince = limit;
}
@Override
public List<ObjectId> getDeepenNots() {
return deepenNots;
}
/**
* Mark objects that the client specified using
* --shallow-exclude. Objects that are not commits have no
* effect.
*
* @param deepenNots specified objects
* @since 5.2
*/
public void setDeepenNots(List<ObjectId> deepenNots) {
this.deepenNots = Objects.requireNonNull(deepenNots);
}
@Override
public RevFlag getUnshallowFlag() {
return UNSHALLOW;
}
@Override
public RevFlag getReinterestingFlag() {
return REINTERESTING;
}
@Override
public RevFlag getDeepenNotFlag() {
return DEEPEN_NOT;
}
/**
* @since 4.5
*/
@Override
public ObjectWalk toObjectWalkWithSameObjects() {
ObjectWalk ow = new ObjectWalk(reader, depth);
ow.deepenSince = deepenSince;
ow.deepenNots = deepenNots;
ow.objects = objects;
ow.freeFlags = freeFlags;
return ow;
}
}
/** Subclass of ObjectWalk that performs depth filtering. */
public class ObjectWalk extends org.eclipse.jgit.revwalk.ObjectWalk implements DepthWalk {
private final int depth;
private int deepenSince;
private List<ObjectId> deepenNots;
private final RevFlag UNSHALLOW;
private final RevFlag REINTERESTING;
private final RevFlag DEEPEN_NOT;
/**
* @param repo Repository to walk
* @param depth Maximum depth to return
*/
public ObjectWalk(Repository repo, int depth) {
super(repo);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* @param or Object Reader
* @param depth Maximum depth to return
*/
public ObjectWalk(ObjectReader or, int depth) {
super(or);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* Mark a root commit (i.e., one whose depth should be considered 0.)
*
* @param o
* Commit to mark
* @throws IOException
* @throws IncorrectObjectTypeException
* @throws MissingObjectException
*/
public void markRoot(RevObject o) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
RevObject c = o;
while (c instanceof RevTag) {
c = ((RevTag) c).getObject();
parseHeaders(c);
}
if (c instanceof Commit)
((Commit) c).depth = 0;
super.markStart(o);
}
/**
* Mark an element which used to be shallow in the client, but which
* should now be considered a full commit. Any ancestors of this commit
* should be included in the walk, even if they are the ancestor of an
* uninteresting commit.
*
* @param c
* Commit to mark
* @throws MissingObjectException
* @throws IncorrectObjectTypeException
* @throws IOException
*/
public void markUnshallow(RevObject c) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
if (c instanceof RevCommit)
c.add(UNSHALLOW);
super.markStart(c);
}
@Override
protected RevCommit createCommit(AnyObjectId id) {
return new Commit(id);
}
@Override
public int getDepth() {
return depth;
}
@Override
public int getDeepenSince() {
return deepenSince;
}
@Override
public List<ObjectId> getDeepenNots() {
return deepenNots;
}
@Override
public RevFlag getUnshallowFlag() {
return UNSHALLOW;
}
@Override
public RevFlag getReinterestingFlag() {
return REINTERESTING;
}
@Override
public RevFlag getDeepenNotFlag() {
return DEEPEN_NOT;
}
}
}
| theonedev/onedev | server-core/src/main/java/org/eclipse/jgit/revwalk/DepthWalk.java | 2,855 | /**
* Sets the deepen-since value.
*
* @param limit
* new deepen-since value
* @since 5.2
*/ | block_comment | nl | /*
* Copyright (C) 2010, Garmin International
* Copyright (C) 2010, Matt Fischer <[email protected]> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.revwalk;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
/**
* Interface for revision walkers that perform depth filtering.
*/
public interface DepthWalk {
/**
* Get depth to filter to.
*
* @return Depth to filter to.
*/
int getDepth();
/**
* @return the deepen-since value; if not 0, this walk only returns commits
* whose commit time is at or after this limit
* @since 5.2
*/
default int getDeepenSince() {
return 0;
}
/**
* @return the objects specified by the client using --shallow-exclude
* @since 5.2
*/
default List<ObjectId> getDeepenNots() {
return Collections.emptyList();
}
/** @return flag marking commits that should become unshallow. */
/**
* Get flag marking commits that should become unshallow.
*
* @return flag marking commits that should become unshallow.
*/
RevFlag getUnshallowFlag();
/**
* Get flag marking commits that are interesting again.
*
* @return flag marking commits that are interesting again.
*/
RevFlag getReinterestingFlag();
/**
* @return flag marking commits that are to be excluded because of --shallow-exclude
* @since 5.2
*/
RevFlag getDeepenNotFlag();
/** RevCommit with a depth (in commits) from a root. */
public static class Commit extends RevCommit {
/** Depth of this commit in the graph, via shortest path. */
int depth;
boolean isBoundary;
/**
* True if this commit was excluded due to a shallow fetch
* setting. All its children are thus boundary commits.
*/
boolean makesChildBoundary;
/** @return depth of this commit, as found by the shortest path. */
public int getDepth() {
return depth;
}
/**
* @return true if at least one of this commit's parents was excluded
* due to a shallow fetch setting, false otherwise
* @since 5.2
*/
public boolean isBoundary() {
return isBoundary;
}
/**
* Initialize a new commit.
*
* @param id
* object name for the commit.
*/
protected Commit(AnyObjectId id) {
super(id);
depth = -1;
}
}
/** Subclass of RevWalk that performs depth filtering. */
public class RevWalk extends org.eclipse.jgit.revwalk.RevWalk implements DepthWalk {
private final int depth;
private int deepenSince;
private List<ObjectId> deepenNots;
private final RevFlag UNSHALLOW;
private final RevFlag REINTERESTING;
private final RevFlag DEEPEN_NOT;
/**
* @param repo Repository to walk
* @param depth Maximum depth to return
*/
public RevWalk(Repository repo, int depth) {
super(repo);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* @param or ObjectReader to use
* @param depth Maximum depth to return
*/
public RevWalk(ObjectReader or, int depth) {
super(or);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* Mark a root commit (i.e., one whose depth should be considered 0.)
*
* @param c
* Commit to mark
* @throws IOException
* @throws IncorrectObjectTypeException
* @throws MissingObjectException
*/
public void markRoot(RevCommit c) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
if (c instanceof Commit)
((Commit) c).depth = 0;
super.markStart(c);
}
@Override
protected RevCommit createCommit(AnyObjectId id) {
return new Commit(id);
}
@Override
public int getDepth() {
return depth;
}
@Override
public int getDeepenSince() {
return deepenSince;
}
/**
* Sets the deepen-since<SUF>*/
public void setDeepenSince(int limit) {
deepenSince = limit;
}
@Override
public List<ObjectId> getDeepenNots() {
return deepenNots;
}
/**
* Mark objects that the client specified using
* --shallow-exclude. Objects that are not commits have no
* effect.
*
* @param deepenNots specified objects
* @since 5.2
*/
public void setDeepenNots(List<ObjectId> deepenNots) {
this.deepenNots = Objects.requireNonNull(deepenNots);
}
@Override
public RevFlag getUnshallowFlag() {
return UNSHALLOW;
}
@Override
public RevFlag getReinterestingFlag() {
return REINTERESTING;
}
@Override
public RevFlag getDeepenNotFlag() {
return DEEPEN_NOT;
}
/**
* @since 4.5
*/
@Override
public ObjectWalk toObjectWalkWithSameObjects() {
ObjectWalk ow = new ObjectWalk(reader, depth);
ow.deepenSince = deepenSince;
ow.deepenNots = deepenNots;
ow.objects = objects;
ow.freeFlags = freeFlags;
return ow;
}
}
/** Subclass of ObjectWalk that performs depth filtering. */
public class ObjectWalk extends org.eclipse.jgit.revwalk.ObjectWalk implements DepthWalk {
private final int depth;
private int deepenSince;
private List<ObjectId> deepenNots;
private final RevFlag UNSHALLOW;
private final RevFlag REINTERESTING;
private final RevFlag DEEPEN_NOT;
/**
* @param repo Repository to walk
* @param depth Maximum depth to return
*/
public ObjectWalk(Repository repo, int depth) {
super(repo);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* @param or Object Reader
* @param depth Maximum depth to return
*/
public ObjectWalk(ObjectReader or, int depth) {
super(or);
this.depth = depth;
this.deepenNots = Collections.emptyList();
this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
this.DEEPEN_NOT = newFlag("DEEPEN_NOT"); //$NON-NLS-1$
}
/**
* Mark a root commit (i.e., one whose depth should be considered 0.)
*
* @param o
* Commit to mark
* @throws IOException
* @throws IncorrectObjectTypeException
* @throws MissingObjectException
*/
public void markRoot(RevObject o) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
RevObject c = o;
while (c instanceof RevTag) {
c = ((RevTag) c).getObject();
parseHeaders(c);
}
if (c instanceof Commit)
((Commit) c).depth = 0;
super.markStart(o);
}
/**
* Mark an element which used to be shallow in the client, but which
* should now be considered a full commit. Any ancestors of this commit
* should be included in the walk, even if they are the ancestor of an
* uninteresting commit.
*
* @param c
* Commit to mark
* @throws MissingObjectException
* @throws IncorrectObjectTypeException
* @throws IOException
*/
public void markUnshallow(RevObject c) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
if (c instanceof RevCommit)
c.add(UNSHALLOW);
super.markStart(c);
}
@Override
protected RevCommit createCommit(AnyObjectId id) {
return new Commit(id);
}
@Override
public int getDepth() {
return depth;
}
@Override
public int getDeepenSince() {
return deepenSince;
}
@Override
public List<ObjectId> getDeepenNots() {
return deepenNots;
}
@Override
public RevFlag getUnshallowFlag() {
return UNSHALLOW;
}
@Override
public RevFlag getReinterestingFlag() {
return REINTERESTING;
}
@Override
public RevFlag getDeepenNotFlag() {
return DEEPEN_NOT;
}
}
}
|
30800_29 | import java.util.*;
import java.text.*;
public class SogyoClockGoed {
public static void main(String[] args){
String timeConstruction = "";
int scale = 1;
// Get parameters from console
for(int i = 0; i < args.length; i++){
if(args[i].equals("-s")){
int value = Integer.parseInt(args[i+1]);
if(value < 1 || value > 5){
throw new IllegalArgumentException("Pick a size between 1 and 5.");
} else {
System.out.println("Size: " + value);
scale = value;
}
}
if(args[i].equals("-12") || args[i].equals("-24")){
timeConstruction = args[i];
} else {
timeConstruction = "-24";
}
}
System.out.println(timeConstruction);
String[] A = {
" - ",
"| |",
" - ",
"| |",
" "
};
String[] P = {
" - ",
"| |",
" - ",
"| ",
" "
};
String[] zero = {
" - ",
"| |",
" ",
"| |",
" - "
};
String[] one = {
" ",
" |",
" ",
" |",
" "
};
String[] two = {
" - ",
" |",
" - ",
"| ",
" - "
};
String[] three = {
" - ",
" |",
" - ",
" |",
" - "
};
String[] four = {
" ",
"| |",
" - ",
" |",
" "
};
String[] five = {
" - ",
"| ",
" - ",
" |",
" - "
};
String[] six = {
" - ",
"| ",
" - ",
"| |",
" - "
};
String[] seven = {
" - ",
" |",
" ",
" |",
" "
};
String[] eight = {
" - ",
"| |",
" - ",
"| |",
" - "
};
String[] nine = {
" - ",
"| |",
" - ",
" |",
" - "
};
// Set up date etc, check for AM/PM
boolean am = false;
String time = "";
char[] timeArr = new char[4];
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("hhmm");
// Mn 12/24 uurs tijdsnotering klopt nog niet, die is omgedraaid, moet ik nog fixen
if(timeConstruction.equals("-12")){
ft = new SimpleDateFormat ("HHmm a");
time = ft.format(dNow);
String[] timeSplit = time.split(" ");
// check if am or pm
if(timeSplit[1].equals("AM")){
am = true;
}
timeArr = timeSplit[0].toCharArray();
} else {
time = ft.format(dNow);
timeArr = time.toCharArray();
}
/** De timeArr is een array met de characters van de tijd, dus als het 12:51 is, is het {'1','2','5','1'};
Eigenlijk is het ook makkelijker om een List<List<String>> te maken, want dan kan je makkelijker
de A/P toevoegen als dat nodig is.
Ik heb ook de colon tussen de cijfers niet toegevoegd, maar dat zou je met een List<List<String>> dus
ook makkelijker kunnen doen */
String[][] arrays = new String[4][];
// voeg het corresponderende getal toe aan de array
for(int i = 0; i < timeArr.length; i++){
switch(timeArr[i]){
case '0':
arrays[i] = zero;
break;
case '1':
arrays[i] = one;
break;
case '2':
arrays[i] = two;
break;
case '3':
arrays[i] = three;
break;
case '4':
arrays[i] = four;
break;
case '5':
arrays[i] = five;
break;
case '6':
arrays[i] = six;
break;
case '7':
arrays[i] = seven;
break;
case '8':
arrays[i] = eight;
break;
case '9':
arrays[i] = nine;
break;
}
}
// Initialize een array voor de formattering, maakt het makkelijker om zometeen te printen
String[][] arraysFormatted = new String[5][4];
// loop door de tijd array heen, dus als voorbeeld: 12:51
for(int j = 0; j < arrays[0].length; j++){
// arrays[0].length is hier dus '1', dan '2', dan '5', dan '1'
for(int i = 0; i < arrays.length; i++){
// loop dan door de visuele representatie van dat cijfer, dus voor '1' is dat
// String[] one ={
// " ",
// " |",
// " ",
// " |",
// " "
// };
// zet de visuele representatie om in een charArray, want we moeten extra dashes/pipes/spaties toevoegen
// op basis van de scale(/size)
char[] charArray = arrays[i][j].toCharArray();
String dash = "";
String pipe = "";
// het element voor de tweede iteratie van het getal '1' is:
// {' ', ' ','|'}
// space, space, pipe
// als het element een dash bevat, moeten we extra dashes toevoegen
if(arrays[i][j].contains("-")){
for(int k = 0; k < charArray.length; k++){
// een dash is altijd alleen maar in de middelste 'tile' van de originele charArray
if(k == 1){
// herhaal het aantal dashes gebaseerd op de scale(/size)
for(int l = 0; l < scale; l++){
dash += charArray[k];
}
} else {
dash += charArray[k];
}
}
// voeg spaties toe
for(int l = 0; l < scale-1; l++){
dash += " ";
}
// voeg de dash toe aan de geformatteerde array, dat maakt het makkelijker om hem te printen
arraysFormatted[j][i] = dash;
// voor pipes doe je eigenlijk hetzelfde, maar bij een pipe moet je spaties in het midden toevoegen
// omdat er in het midden nooit een pipe kan zijn, dus kan je daar rustig spaties toevoegen
} else {
for(int k = 0; k < charArray.length; k++){
if(k == 1){
for(int l = 0; l < scale-1; l++){
pipe += " ";
}
}
pipe += charArray[k];
}
for(int l = 0; l < scale-1; l++){
pipe += " ";
}
arraysFormatted[j][i] = pipe;
}
}
}
// dan loop je door de geformatteerde array heen, en hoef je hem eigenlijk alleen nog maar te printen
for(int i = 0; i < arraysFormatted.length; i++){
if(i % 2 != 0){
/** Hier print je de verticale rijen, de dashes zijn al verbreed, maar de pipes nog niet
dus dat gebeurt hier. De rij i % 2 != 0 bevat altijd een pipe namelijk */
for(int k = 0; k < scale; k++){
for(int j = 0; j < arraysFormatted[i].length; j++){
System.out.print(arraysFormatted[i][j]);
}
System.out.println();
}
} else {
/** Als het de rij met dashes is hoeven we die alleen te printen, omdat er al extra dashes
toegevoegd zijn (op basis van de scale/size) */
for(int j = 0; j < arraysFormatted[i].length; j++){
System.out.print(arraysFormatted[i][j]);
}
System.out.println();
}
}
}
}
/** De oorspronkelijke array zag er zo uit, (uitgaand van de tijd 12:51)
String[][] arrays = {
{ " ", " |", " ", " |", " " }, // 1
{ " - ", " |", " - ", "| ", " - " }, // 2
{ " - ", "| ", " - ", " |", " - " }, // 5
{ " ", " |", " ", " |", " " }, // 1
};
Dus bevat 4 elementen, en elk element heeft 5 sub elementen
Dat is vet moeilijk om te printen, dus heb ik het omgedraaid naar
een array met 5 elementen, met 4 sub elementen, namelijk:
String[][] arraysFormatted = {
1 2 5 1
{" ", " - ", " - ", " " },
{" |", " |", "| ", " |" },
{" ", " - ", " - ", " " },
{" |", "| ", " |", " |" },
{" ", " - ", " - ", " " }
}
*/
| thepassle/software-engineering-training | java-exercises/opdracht9-clock/SogyoClockGoed.java | 3,002 | /** Hier print je de verticale rijen, de dashes zijn al verbreed, maar de pipes nog niet
dus dat gebeurt hier. De rij i % 2 != 0 bevat altijd een pipe namelijk */ | block_comment | nl | import java.util.*;
import java.text.*;
public class SogyoClockGoed {
public static void main(String[] args){
String timeConstruction = "";
int scale = 1;
// Get parameters from console
for(int i = 0; i < args.length; i++){
if(args[i].equals("-s")){
int value = Integer.parseInt(args[i+1]);
if(value < 1 || value > 5){
throw new IllegalArgumentException("Pick a size between 1 and 5.");
} else {
System.out.println("Size: " + value);
scale = value;
}
}
if(args[i].equals("-12") || args[i].equals("-24")){
timeConstruction = args[i];
} else {
timeConstruction = "-24";
}
}
System.out.println(timeConstruction);
String[] A = {
" - ",
"| |",
" - ",
"| |",
" "
};
String[] P = {
" - ",
"| |",
" - ",
"| ",
" "
};
String[] zero = {
" - ",
"| |",
" ",
"| |",
" - "
};
String[] one = {
" ",
" |",
" ",
" |",
" "
};
String[] two = {
" - ",
" |",
" - ",
"| ",
" - "
};
String[] three = {
" - ",
" |",
" - ",
" |",
" - "
};
String[] four = {
" ",
"| |",
" - ",
" |",
" "
};
String[] five = {
" - ",
"| ",
" - ",
" |",
" - "
};
String[] six = {
" - ",
"| ",
" - ",
"| |",
" - "
};
String[] seven = {
" - ",
" |",
" ",
" |",
" "
};
String[] eight = {
" - ",
"| |",
" - ",
"| |",
" - "
};
String[] nine = {
" - ",
"| |",
" - ",
" |",
" - "
};
// Set up date etc, check for AM/PM
boolean am = false;
String time = "";
char[] timeArr = new char[4];
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("hhmm");
// Mn 12/24 uurs tijdsnotering klopt nog niet, die is omgedraaid, moet ik nog fixen
if(timeConstruction.equals("-12")){
ft = new SimpleDateFormat ("HHmm a");
time = ft.format(dNow);
String[] timeSplit = time.split(" ");
// check if am or pm
if(timeSplit[1].equals("AM")){
am = true;
}
timeArr = timeSplit[0].toCharArray();
} else {
time = ft.format(dNow);
timeArr = time.toCharArray();
}
/** De timeArr is een array met de characters van de tijd, dus als het 12:51 is, is het {'1','2','5','1'};
Eigenlijk is het ook makkelijker om een List<List<String>> te maken, want dan kan je makkelijker
de A/P toevoegen als dat nodig is.
Ik heb ook de colon tussen de cijfers niet toegevoegd, maar dat zou je met een List<List<String>> dus
ook makkelijker kunnen doen */
String[][] arrays = new String[4][];
// voeg het corresponderende getal toe aan de array
for(int i = 0; i < timeArr.length; i++){
switch(timeArr[i]){
case '0':
arrays[i] = zero;
break;
case '1':
arrays[i] = one;
break;
case '2':
arrays[i] = two;
break;
case '3':
arrays[i] = three;
break;
case '4':
arrays[i] = four;
break;
case '5':
arrays[i] = five;
break;
case '6':
arrays[i] = six;
break;
case '7':
arrays[i] = seven;
break;
case '8':
arrays[i] = eight;
break;
case '9':
arrays[i] = nine;
break;
}
}
// Initialize een array voor de formattering, maakt het makkelijker om zometeen te printen
String[][] arraysFormatted = new String[5][4];
// loop door de tijd array heen, dus als voorbeeld: 12:51
for(int j = 0; j < arrays[0].length; j++){
// arrays[0].length is hier dus '1', dan '2', dan '5', dan '1'
for(int i = 0; i < arrays.length; i++){
// loop dan door de visuele representatie van dat cijfer, dus voor '1' is dat
// String[] one ={
// " ",
// " |",
// " ",
// " |",
// " "
// };
// zet de visuele representatie om in een charArray, want we moeten extra dashes/pipes/spaties toevoegen
// op basis van de scale(/size)
char[] charArray = arrays[i][j].toCharArray();
String dash = "";
String pipe = "";
// het element voor de tweede iteratie van het getal '1' is:
// {' ', ' ','|'}
// space, space, pipe
// als het element een dash bevat, moeten we extra dashes toevoegen
if(arrays[i][j].contains("-")){
for(int k = 0; k < charArray.length; k++){
// een dash is altijd alleen maar in de middelste 'tile' van de originele charArray
if(k == 1){
// herhaal het aantal dashes gebaseerd op de scale(/size)
for(int l = 0; l < scale; l++){
dash += charArray[k];
}
} else {
dash += charArray[k];
}
}
// voeg spaties toe
for(int l = 0; l < scale-1; l++){
dash += " ";
}
// voeg de dash toe aan de geformatteerde array, dat maakt het makkelijker om hem te printen
arraysFormatted[j][i] = dash;
// voor pipes doe je eigenlijk hetzelfde, maar bij een pipe moet je spaties in het midden toevoegen
// omdat er in het midden nooit een pipe kan zijn, dus kan je daar rustig spaties toevoegen
} else {
for(int k = 0; k < charArray.length; k++){
if(k == 1){
for(int l = 0; l < scale-1; l++){
pipe += " ";
}
}
pipe += charArray[k];
}
for(int l = 0; l < scale-1; l++){
pipe += " ";
}
arraysFormatted[j][i] = pipe;
}
}
}
// dan loop je door de geformatteerde array heen, en hoef je hem eigenlijk alleen nog maar te printen
for(int i = 0; i < arraysFormatted.length; i++){
if(i % 2 != 0){
/** Hier print je<SUF>*/
for(int k = 0; k < scale; k++){
for(int j = 0; j < arraysFormatted[i].length; j++){
System.out.print(arraysFormatted[i][j]);
}
System.out.println();
}
} else {
/** Als het de rij met dashes is hoeven we die alleen te printen, omdat er al extra dashes
toegevoegd zijn (op basis van de scale/size) */
for(int j = 0; j < arraysFormatted[i].length; j++){
System.out.print(arraysFormatted[i][j]);
}
System.out.println();
}
}
}
}
/** De oorspronkelijke array zag er zo uit, (uitgaand van de tijd 12:51)
String[][] arrays = {
{ " ", " |", " ", " |", " " }, // 1
{ " - ", " |", " - ", "| ", " - " }, // 2
{ " - ", "| ", " - ", " |", " - " }, // 5
{ " ", " |", " ", " |", " " }, // 1
};
Dus bevat 4 elementen, en elk element heeft 5 sub elementen
Dat is vet moeilijk om te printen, dus heb ik het omgedraaid naar
een array met 5 elementen, met 4 sub elementen, namelijk:
String[][] arraysFormatted = {
1 2 5 1
{" ", " - ", " - ", " " },
{" |", " |", "| ", " |" },
{" ", " - ", " - ", " " },
{" |", "| ", " |", " |" },
{" ", " - ", " - ", " " }
}
*/
|
26982_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.theresasogunle;
import static com.github.theresasogunle.Encryption.encryptData;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Theresa
*/
public class AlternativePayment {
ApiConnection apiConnection;
Encryption e=new Encryption();
private String accountnumber,accountbank,currency,country,
amount,firstname,lastname,
pin,email,IP,txRef,phonenumber,orderRef,network,
flwRef;
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
// charge customers using nigerian USSD for GTB and Zenith Bank,Ghana mobile money and Kenya Mpesa
public JSONObject chargeNigerianUssd () {
//getting charge endpoint
JSONObject json=new JSONObject();
try{
json.put("accountnumber", this.getAccountnumber());
json.put("accountbank", this.getAccountbank());
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("payment_type", "ussd");
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
public JSONObject chargeGhanaMobileMoney () {
//getting charge endpoint
JSONObject json=new JSONObject();
try{
json.put("orderRef",this.getOrderRef());
json.put("network", this.getNetwork());
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("payment_type", "mobilemoneygh");
json.put("is_mobile_money_gh", "1");
json.put("phonenumber",this.getPhonenumber());
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
public JSONObject chargeKenyaMpesa () {
//getting charge endpoint
JSONObject json=new JSONObject();
try{
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("orderRef", this.getOrderRef());
json.put("phonenumber", this.getPhonenumber());
json.put("payment_type", "mpesa");
json.put("is_mpesa", "1");
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @param txref
* @param flwref
* @return JSONObject
*/
//to requery transaction for ghana mobile money,kenya mpesa and nigerian ussd using xquery
/**
* @return the accountnumber
*/
public String getAccountnumber() {
return accountnumber;
}
/**
* @param accountnumber the accountnumber to set
* @return AlternativePayment
*/
public AlternativePayment setAccountnumber(String accountnumber) {
this.accountnumber = accountnumber;
return this;
}
/**
* @return the accountbank
*/
public String getAccountbank() {
return accountbank;
}
/**
* @param accountbank the accountbank to set
* @return AlternativePayment
*/
public AlternativePayment setAccountbank(String accountbank) {
this.accountbank = accountbank;
return this;
}
/**
* @return the currency
*/
public String getCurrency() {
return currency;
}
/**
* @param currency the currency to set
* @return AlternativePayment
*/
public AlternativePayment setCurrency(String currency) {
this.currency = currency;
return this;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
* @return AlternativePayment
*/
public AlternativePayment setCountry(String country) {
this.country = country;
return this;
}
/**
* @return the amount
*/
public String getAmount() {
return amount;
}
/**
* @param amount the amount to set
* @return AlternativePayment
*/
public AlternativePayment setAmount(String amount) {
this.amount = amount;
return this;
}
/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* @param firstname the firstname to set
* @return AlternativePayment
*/
public AlternativePayment setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* @param lastname the lastname to set
* @return AlternativePayment
*/
public AlternativePayment setLastname(String lastname) {
this.lastname = lastname;
return this;
}
/**
* @return the pin
*/
public String getPin() {
return pin;
}
/**
* @param pin the pin to set
* @return AlternativePayment
*/
public AlternativePayment setPin(String pin) {
this.pin = pin;
return this;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
* @return AlternativePayment
*/
public AlternativePayment setEmail(String email) {
this.email = email;
return this;
}
/**
* @return the IP
*/
public String getIP() {
return IP;
}
/**
* @param IP the IP to set
* @return AlternativePayment
*/
public AlternativePayment setIP(String IP) {
this.IP = IP;
return this;
}
/**
* @return the txRef
*/
public String getTxRef() {
return txRef;
}
/**
* @param txRef the txRef to set
* @return AlternativePayment
*/
public AlternativePayment setTxRef(String txRef) {
this.txRef = txRef;
return this;
}
/**
* @return the phonenumber
*/
public String getPhonenumber() {
return phonenumber;
}
/**
* @param phonenumber the phonenumber to set
* @return AlternativePayment
*/
public AlternativePayment setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
return this;
}
/**
* @return the orderRef
*/
public String getOrderRef() {
return orderRef;
}
/**
* @param orderRef the orderRef to set
* @return AlternativePayment
*/
public AlternativePayment setOrderRef(String orderRef) {
this.orderRef = orderRef;
return this;
}
/**
* @return the network
*/
public String getNetwork() {
return network;
}
/**
* @param network the network to set
* @return AlternativePayment
*/
public AlternativePayment setNetwork(String network) {
this.network = network;
return this;
}
/**
* @return the flwRef
*/
public String getFlwRef() {
return flwRef;
}
/**
* @param flwRef the flwRef to set
* @return AlternativePayment
*/
public AlternativePayment setFlwRef(String flwRef) {
this.flwRef = flwRef;
return this;
}
}
| theresasogunle/Rave-Java-Library | src/main/java/com/github/theresasogunle/AlternativePayment.java | 2,757 | //getting charge endpoint | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.theresasogunle;
import static com.github.theresasogunle.Encryption.encryptData;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Theresa
*/
public class AlternativePayment {
ApiConnection apiConnection;
Encryption e=new Encryption();
private String accountnumber,accountbank,currency,country,
amount,firstname,lastname,
pin,email,IP,txRef,phonenumber,orderRef,network,
flwRef;
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
// charge customers using nigerian USSD for GTB and Zenith Bank,Ghana mobile money and Kenya Mpesa
public JSONObject chargeNigerianUssd () {
//getting charge<SUF>
JSONObject json=new JSONObject();
try{
json.put("accountnumber", this.getAccountnumber());
json.put("accountbank", this.getAccountbank());
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("payment_type", "ussd");
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
public JSONObject chargeGhanaMobileMoney () {
//getting charge endpoint
JSONObject json=new JSONObject();
try{
json.put("orderRef",this.getOrderRef());
json.put("network", this.getNetwork());
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("payment_type", "mobilemoneygh");
json.put("is_mobile_money_gh", "1");
json.put("phonenumber",this.getPhonenumber());
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @throws JSONException it throws JSON exception
* @return JSONObject
*/
public JSONObject chargeKenyaMpesa () {
//getting charge endpoint
JSONObject json=new JSONObject();
try{
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("pin", this.getPin());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("orderRef", this.getOrderRef());
json.put("phonenumber", this.getPhonenumber());
json.put("payment_type", "mpesa");
json.put("is_mpesa", "1");
}catch(JSONException ex){ex.getMessage();}
String message= json.toString();
String encrypt_secret_key=Encryption.getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
/**
*
* @param txref
* @param flwref
* @return JSONObject
*/
//to requery transaction for ghana mobile money,kenya mpesa and nigerian ussd using xquery
/**
* @return the accountnumber
*/
public String getAccountnumber() {
return accountnumber;
}
/**
* @param accountnumber the accountnumber to set
* @return AlternativePayment
*/
public AlternativePayment setAccountnumber(String accountnumber) {
this.accountnumber = accountnumber;
return this;
}
/**
* @return the accountbank
*/
public String getAccountbank() {
return accountbank;
}
/**
* @param accountbank the accountbank to set
* @return AlternativePayment
*/
public AlternativePayment setAccountbank(String accountbank) {
this.accountbank = accountbank;
return this;
}
/**
* @return the currency
*/
public String getCurrency() {
return currency;
}
/**
* @param currency the currency to set
* @return AlternativePayment
*/
public AlternativePayment setCurrency(String currency) {
this.currency = currency;
return this;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
* @return AlternativePayment
*/
public AlternativePayment setCountry(String country) {
this.country = country;
return this;
}
/**
* @return the amount
*/
public String getAmount() {
return amount;
}
/**
* @param amount the amount to set
* @return AlternativePayment
*/
public AlternativePayment setAmount(String amount) {
this.amount = amount;
return this;
}
/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* @param firstname the firstname to set
* @return AlternativePayment
*/
public AlternativePayment setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* @param lastname the lastname to set
* @return AlternativePayment
*/
public AlternativePayment setLastname(String lastname) {
this.lastname = lastname;
return this;
}
/**
* @return the pin
*/
public String getPin() {
return pin;
}
/**
* @param pin the pin to set
* @return AlternativePayment
*/
public AlternativePayment setPin(String pin) {
this.pin = pin;
return this;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
* @return AlternativePayment
*/
public AlternativePayment setEmail(String email) {
this.email = email;
return this;
}
/**
* @return the IP
*/
public String getIP() {
return IP;
}
/**
* @param IP the IP to set
* @return AlternativePayment
*/
public AlternativePayment setIP(String IP) {
this.IP = IP;
return this;
}
/**
* @return the txRef
*/
public String getTxRef() {
return txRef;
}
/**
* @param txRef the txRef to set
* @return AlternativePayment
*/
public AlternativePayment setTxRef(String txRef) {
this.txRef = txRef;
return this;
}
/**
* @return the phonenumber
*/
public String getPhonenumber() {
return phonenumber;
}
/**
* @param phonenumber the phonenumber to set
* @return AlternativePayment
*/
public AlternativePayment setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
return this;
}
/**
* @return the orderRef
*/
public String getOrderRef() {
return orderRef;
}
/**
* @param orderRef the orderRef to set
* @return AlternativePayment
*/
public AlternativePayment setOrderRef(String orderRef) {
this.orderRef = orderRef;
return this;
}
/**
* @return the network
*/
public String getNetwork() {
return network;
}
/**
* @param network the network to set
* @return AlternativePayment
*/
public AlternativePayment setNetwork(String network) {
this.network = network;
return this;
}
/**
* @return the flwRef
*/
public String getFlwRef() {
return flwRef;
}
/**
* @param flwRef the flwRef to set
* @return AlternativePayment
*/
public AlternativePayment setFlwRef(String flwRef) {
this.flwRef = flwRef;
return this;
}
}
|
59862_6 | /**
*/
package org.bbaw.bts.corpus.text.egy.egyDsl.impl;
import org.bbaw.bts.corpus.text.egy.egyDsl.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class EgyDslFactoryImpl extends EFactoryImpl implements EgyDslFactory
{
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static EgyDslFactory init()
{
try
{
EgyDslFactory theEgyDslFactory = (EgyDslFactory)EPackage.Registry.INSTANCE.getEFactory(EgyDslPackage.eNS_URI);
if (theEgyDslFactory != null)
{
return theEgyDslFactory;
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
}
return new EgyDslFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EgyDslFactoryImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass)
{
switch (eClass.getClassifierID())
{
case EgyDslPackage.TEXT_CONTENT: return createTextContent();
case EgyDslPackage.TEXT_ITEM: return createTextItem();
case EgyDslPackage.SENTENCE: return createSentence();
case EgyDslPackage.SENTENCE_ITEM: return createSentenceItem();
case EgyDslPackage.ABSTRACT_MARKER: return createAbstractMarker();
case EgyDslPackage.AMBIVALENCE: return createAmbivalence();
case EgyDslPackage.CASE: return createCase();
case EgyDslPackage.SENTENCE_ITEM_NO_AMBIVALENCE: return createSentenceItemNoAmbivalence();
case EgyDslPackage.MARKER: return createMarker();
case EgyDslPackage.DESTRUCTION_MARKER: return createDestructionMarker();
case EgyDslPackage.WORD: return createWord();
case EgyDslPackage.WORD_PART: return createWordPart();
case EgyDslPackage.WORD_MIDDLE: return createWordMiddle();
case EgyDslPackage.CHARS: return createChars();
case EgyDslPackage.BRACKETS: return createBrackets();
case EgyDslPackage.OVAL: return createOval();
case EgyDslPackage.SERECH: return createSerech();
case EgyDslPackage.CARTOUCHE: return createCartouche();
case EgyDslPackage.NO_CARTOUCHE: return createNoCartouche();
case EgyDslPackage.EXPANDED: return createExpanded();
case EgyDslPackage.ANCIENT_EXPANDED: return createAncientExpanded();
case EgyDslPackage.NO_EXPANDED: return createNoExpanded();
case EgyDslPackage.EMENDATION: return createEmendation();
case EgyDslPackage.NO_EMENDATION: return createNoEmendation();
case EgyDslPackage.DISPUTABLE_READING: return createDisputableReading();
case EgyDslPackage.NO_DISPUTABLE_READING: return createNoDisputableReading();
case EgyDslPackage.LACUNA: return createLacuna();
case EgyDslPackage.NO_LACUNA: return createNoLacuna();
case EgyDslPackage.DELETION: return createDeletion();
case EgyDslPackage.NO_DELETION: return createNoDeletion();
case EgyDslPackage.EXPANDED_COLUMN: return createExpandedColumn();
case EgyDslPackage.NO_EXPANDED_COLUMN: return createNoExpandedColumn();
case EgyDslPackage.RASUR: return createRasur();
case EgyDslPackage.NO_RASUR: return createNoRasur();
case EgyDslPackage.NO_ANCIENT_EXPANDED: return createNoAncientExpanded();
case EgyDslPackage.RESTORATION_OVER_RASUR: return createRestorationOverRasur();
case EgyDslPackage.NO_RESTORATION_OVER_RASUR: return createNoRestorationOverRasur();
case EgyDslPackage.PARTIAL_DESTRUCTION: return createPartialDestruction();
case EgyDslPackage.NO_PARTIAL_DESTRUCTION: return createNoPartialDestruction();
case EgyDslPackage.INTERFIX: return createInterfix();
case EgyDslPackage.INTERFIX_LEXICAL: return createInterfixLexical();
case EgyDslPackage.INTERFIX_FLEXION: return createInterfixFlexion();
case EgyDslPackage.INTERFIX_SUFFIX_PRONOM_LEXICAL: return createInterfixSuffixPronomLexical();
case EgyDslPackage.INTERFIX_PREFIX_NON_LEXICAL: return createInterfixPrefixNonLexical();
case EgyDslPackage.INTERFIX_PREFIX_LEXICAL: return createInterfixPrefixLexical();
case EgyDslPackage.INTERFIX_CONNECTION_SYLLABIC_GROUP: return createInterfixConnectionSyllabicGroup();
case EgyDslPackage.INTERFIX_COMPOUND_WORDS: return createInterfixCompoundWords();
case EgyDslPackage.INTERFIX_PHONETICAL_COMPLEMENT: return createInterfixPhoneticalComplement();
case EgyDslPackage.VERS_MARKER: return createVersMarker();
case EgyDslPackage.EMENDATION_VERS_MARKER: return createEmendationVersMarker();
case EgyDslPackage.DISPUTABLE_VERS_MARKER: return createDisputableVersMarker();
case EgyDslPackage.DELETED_VERS_MARKER: return createDeletedVersMarker();
case EgyDslPackage.DESTROYED_VERS_MARKER: return createDestroyedVersMarker();
case EgyDslPackage.DESTROYED_VERS_FRONTIER_MARKER: return createDestroyedVersFrontierMarker();
case EgyDslPackage.PARTIAL_DESTROYED_VERS_MARKER: return createPartialDestroyedVersMarker();
case EgyDslPackage.MISSING_VERS_MARKER: return createMissingVersMarker();
case EgyDslPackage.RESTORATION_OVER_RASUR_MARKER: return createRestorationOverRasurMarker();
case EgyDslPackage.ANCIENT_EXPANDED_MARKER: return createAncientExpandedMarker();
case EgyDslPackage.RASUR_MARKER: return createRasurMarker();
case EgyDslPackage.VERS_FRONTIER_MARKER: return createVersFrontierMarker();
case EgyDslPackage.VERSBREAK_MARKER: return createVersbreakMarker();
case EgyDslPackage.BROKEN_VERSBREAK_MARKER: return createBrokenVersbreakMarker();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TextContent createTextContent()
{
TextContentImpl textContent = new TextContentImpl();
return textContent;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TextItem createTextItem()
{
TextItemImpl textItem = new TextItemImpl();
return textItem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Sentence createSentence()
{
SentenceImpl sentence = new SentenceImpl();
return sentence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SentenceItem createSentenceItem()
{
SentenceItemImpl sentenceItem = new SentenceItemImpl();
return sentenceItem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AbstractMarker createAbstractMarker()
{
AbstractMarkerImpl abstractMarker = new AbstractMarkerImpl();
return abstractMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Ambivalence createAmbivalence()
{
AmbivalenceImpl ambivalence = new AmbivalenceImpl();
return ambivalence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Case createCase()
{
CaseImpl case_ = new CaseImpl();
return case_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SentenceItemNoAmbivalence createSentenceItemNoAmbivalence()
{
SentenceItemNoAmbivalenceImpl sentenceItemNoAmbivalence = new SentenceItemNoAmbivalenceImpl();
return sentenceItemNoAmbivalence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Marker createMarker()
{
MarkerImpl marker = new MarkerImpl();
return marker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestructionMarker createDestructionMarker()
{
DestructionMarkerImpl destructionMarker = new DestructionMarkerImpl();
return destructionMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Word createWord()
{
WordImpl word = new WordImpl();
return word;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WordPart createWordPart()
{
WordPartImpl wordPart = new WordPartImpl();
return wordPart;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WordMiddle createWordMiddle()
{
WordMiddleImpl wordMiddle = new WordMiddleImpl();
return wordMiddle;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Chars createChars()
{
CharsImpl chars = new CharsImpl();
return chars;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Brackets createBrackets()
{
BracketsImpl brackets = new BracketsImpl();
return brackets;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Oval createOval()
{
OvalImpl oval = new OvalImpl();
return oval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Serech createSerech()
{
SerechImpl serech = new SerechImpl();
return serech;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Cartouche createCartouche()
{
CartoucheImpl cartouche = new CartoucheImpl();
return cartouche;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoCartouche createNoCartouche()
{
NoCartoucheImpl noCartouche = new NoCartoucheImpl();
return noCartouche;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Expanded createExpanded()
{
ExpandedImpl expanded = new ExpandedImpl();
return expanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AncientExpanded createAncientExpanded()
{
AncientExpandedImpl ancientExpanded = new AncientExpandedImpl();
return ancientExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoExpanded createNoExpanded()
{
NoExpandedImpl noExpanded = new NoExpandedImpl();
return noExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Emendation createEmendation()
{
EmendationImpl emendation = new EmendationImpl();
return emendation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoEmendation createNoEmendation()
{
NoEmendationImpl noEmendation = new NoEmendationImpl();
return noEmendation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisputableReading createDisputableReading()
{
DisputableReadingImpl disputableReading = new DisputableReadingImpl();
return disputableReading;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoDisputableReading createNoDisputableReading()
{
NoDisputableReadingImpl noDisputableReading = new NoDisputableReadingImpl();
return noDisputableReading;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Lacuna createLacuna()
{
LacunaImpl lacuna = new LacunaImpl();
return lacuna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoLacuna createNoLacuna()
{
NoLacunaImpl noLacuna = new NoLacunaImpl();
return noLacuna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Deletion createDeletion()
{
DeletionImpl deletion = new DeletionImpl();
return deletion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoDeletion createNoDeletion()
{
NoDeletionImpl noDeletion = new NoDeletionImpl();
return noDeletion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ExpandedColumn createExpandedColumn()
{
ExpandedColumnImpl expandedColumn = new ExpandedColumnImpl();
return expandedColumn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoExpandedColumn createNoExpandedColumn()
{
NoExpandedColumnImpl noExpandedColumn = new NoExpandedColumnImpl();
return noExpandedColumn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Rasur createRasur()
{
RasurImpl rasur = new RasurImpl();
return rasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoRasur createNoRasur()
{
NoRasurImpl noRasur = new NoRasurImpl();
return noRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoAncientExpanded createNoAncientExpanded()
{
NoAncientExpandedImpl noAncientExpanded = new NoAncientExpandedImpl();
return noAncientExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RestorationOverRasur createRestorationOverRasur()
{
RestorationOverRasurImpl restorationOverRasur = new RestorationOverRasurImpl();
return restorationOverRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoRestorationOverRasur createNoRestorationOverRasur()
{
NoRestorationOverRasurImpl noRestorationOverRasur = new NoRestorationOverRasurImpl();
return noRestorationOverRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PartialDestruction createPartialDestruction()
{
PartialDestructionImpl partialDestruction = new PartialDestructionImpl();
return partialDestruction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoPartialDestruction createNoPartialDestruction()
{
NoPartialDestructionImpl noPartialDestruction = new NoPartialDestructionImpl();
return noPartialDestruction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Interfix createInterfix()
{
InterfixImpl interfix = new InterfixImpl();
return interfix;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixLexical createInterfixLexical()
{
InterfixLexicalImpl interfixLexical = new InterfixLexicalImpl();
return interfixLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixFlexion createInterfixFlexion()
{
InterfixFlexionImpl interfixFlexion = new InterfixFlexionImpl();
return interfixFlexion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixSuffixPronomLexical createInterfixSuffixPronomLexical()
{
InterfixSuffixPronomLexicalImpl interfixSuffixPronomLexical = new InterfixSuffixPronomLexicalImpl();
return interfixSuffixPronomLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPrefixNonLexical createInterfixPrefixNonLexical()
{
InterfixPrefixNonLexicalImpl interfixPrefixNonLexical = new InterfixPrefixNonLexicalImpl();
return interfixPrefixNonLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPrefixLexical createInterfixPrefixLexical()
{
InterfixPrefixLexicalImpl interfixPrefixLexical = new InterfixPrefixLexicalImpl();
return interfixPrefixLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixConnectionSyllabicGroup createInterfixConnectionSyllabicGroup()
{
InterfixConnectionSyllabicGroupImpl interfixConnectionSyllabicGroup = new InterfixConnectionSyllabicGroupImpl();
return interfixConnectionSyllabicGroup;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixCompoundWords createInterfixCompoundWords()
{
InterfixCompoundWordsImpl interfixCompoundWords = new InterfixCompoundWordsImpl();
return interfixCompoundWords;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPhoneticalComplement createInterfixPhoneticalComplement()
{
InterfixPhoneticalComplementImpl interfixPhoneticalComplement = new InterfixPhoneticalComplementImpl();
return interfixPhoneticalComplement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersMarker createVersMarker()
{
VersMarkerImpl versMarker = new VersMarkerImpl();
return versMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EmendationVersMarker createEmendationVersMarker()
{
EmendationVersMarkerImpl emendationVersMarker = new EmendationVersMarkerImpl();
return emendationVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisputableVersMarker createDisputableVersMarker()
{
DisputableVersMarkerImpl disputableVersMarker = new DisputableVersMarkerImpl();
return disputableVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DeletedVersMarker createDeletedVersMarker()
{
DeletedVersMarkerImpl deletedVersMarker = new DeletedVersMarkerImpl();
return deletedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestroyedVersMarker createDestroyedVersMarker()
{
DestroyedVersMarkerImpl destroyedVersMarker = new DestroyedVersMarkerImpl();
return destroyedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestroyedVersFrontierMarker createDestroyedVersFrontierMarker()
{
DestroyedVersFrontierMarkerImpl destroyedVersFrontierMarker = new DestroyedVersFrontierMarkerImpl();
return destroyedVersFrontierMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PartialDestroyedVersMarker createPartialDestroyedVersMarker()
{
PartialDestroyedVersMarkerImpl partialDestroyedVersMarker = new PartialDestroyedVersMarkerImpl();
return partialDestroyedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MissingVersMarker createMissingVersMarker()
{
MissingVersMarkerImpl missingVersMarker = new MissingVersMarkerImpl();
return missingVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RestorationOverRasurMarker createRestorationOverRasurMarker()
{
RestorationOverRasurMarkerImpl restorationOverRasurMarker = new RestorationOverRasurMarkerImpl();
return restorationOverRasurMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AncientExpandedMarker createAncientExpandedMarker()
{
AncientExpandedMarkerImpl ancientExpandedMarker = new AncientExpandedMarkerImpl();
return ancientExpandedMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RasurMarker createRasurMarker()
{
RasurMarkerImpl rasurMarker = new RasurMarkerImpl();
return rasurMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersFrontierMarker createVersFrontierMarker()
{
VersFrontierMarkerImpl versFrontierMarker = new VersFrontierMarkerImpl();
return versFrontierMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersbreakMarker createVersbreakMarker()
{
VersbreakMarkerImpl versbreakMarker = new VersbreakMarkerImpl();
return versbreakMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BrokenVersbreakMarker createBrokenVersbreakMarker()
{
BrokenVersbreakMarkerImpl brokenVersbreakMarker = new BrokenVersbreakMarkerImpl();
return brokenVersbreakMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EgyDslPackage getEgyDslPackage()
{
return (EgyDslPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static EgyDslPackage getPackage()
{
return EgyDslPackage.eINSTANCE;
}
} //EgyDslFactoryImpl
| thesaurus-linguae-aegyptiae/bts | org.bbaw.bts.corpus.text.egy.egydsl/src-gen/org/bbaw/bts/corpus/text/egy/egyDsl/impl/EgyDslFactoryImpl.java | 7,493 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
*/
package org.bbaw.bts.corpus.text.egy.egyDsl.impl;
import org.bbaw.bts.corpus.text.egy.egyDsl.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class EgyDslFactoryImpl extends EFactoryImpl implements EgyDslFactory
{
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static EgyDslFactory init()
{
try
{
EgyDslFactory theEgyDslFactory = (EgyDslFactory)EPackage.Registry.INSTANCE.getEFactory(EgyDslPackage.eNS_URI);
if (theEgyDslFactory != null)
{
return theEgyDslFactory;
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
}
return new EgyDslFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EgyDslFactoryImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass)
{
switch (eClass.getClassifierID())
{
case EgyDslPackage.TEXT_CONTENT: return createTextContent();
case EgyDslPackage.TEXT_ITEM: return createTextItem();
case EgyDslPackage.SENTENCE: return createSentence();
case EgyDslPackage.SENTENCE_ITEM: return createSentenceItem();
case EgyDslPackage.ABSTRACT_MARKER: return createAbstractMarker();
case EgyDslPackage.AMBIVALENCE: return createAmbivalence();
case EgyDslPackage.CASE: return createCase();
case EgyDslPackage.SENTENCE_ITEM_NO_AMBIVALENCE: return createSentenceItemNoAmbivalence();
case EgyDslPackage.MARKER: return createMarker();
case EgyDslPackage.DESTRUCTION_MARKER: return createDestructionMarker();
case EgyDslPackage.WORD: return createWord();
case EgyDslPackage.WORD_PART: return createWordPart();
case EgyDslPackage.WORD_MIDDLE: return createWordMiddle();
case EgyDslPackage.CHARS: return createChars();
case EgyDslPackage.BRACKETS: return createBrackets();
case EgyDslPackage.OVAL: return createOval();
case EgyDslPackage.SERECH: return createSerech();
case EgyDslPackage.CARTOUCHE: return createCartouche();
case EgyDslPackage.NO_CARTOUCHE: return createNoCartouche();
case EgyDslPackage.EXPANDED: return createExpanded();
case EgyDslPackage.ANCIENT_EXPANDED: return createAncientExpanded();
case EgyDslPackage.NO_EXPANDED: return createNoExpanded();
case EgyDslPackage.EMENDATION: return createEmendation();
case EgyDslPackage.NO_EMENDATION: return createNoEmendation();
case EgyDslPackage.DISPUTABLE_READING: return createDisputableReading();
case EgyDslPackage.NO_DISPUTABLE_READING: return createNoDisputableReading();
case EgyDslPackage.LACUNA: return createLacuna();
case EgyDslPackage.NO_LACUNA: return createNoLacuna();
case EgyDslPackage.DELETION: return createDeletion();
case EgyDslPackage.NO_DELETION: return createNoDeletion();
case EgyDslPackage.EXPANDED_COLUMN: return createExpandedColumn();
case EgyDslPackage.NO_EXPANDED_COLUMN: return createNoExpandedColumn();
case EgyDslPackage.RASUR: return createRasur();
case EgyDslPackage.NO_RASUR: return createNoRasur();
case EgyDslPackage.NO_ANCIENT_EXPANDED: return createNoAncientExpanded();
case EgyDslPackage.RESTORATION_OVER_RASUR: return createRestorationOverRasur();
case EgyDslPackage.NO_RESTORATION_OVER_RASUR: return createNoRestorationOverRasur();
case EgyDslPackage.PARTIAL_DESTRUCTION: return createPartialDestruction();
case EgyDslPackage.NO_PARTIAL_DESTRUCTION: return createNoPartialDestruction();
case EgyDslPackage.INTERFIX: return createInterfix();
case EgyDslPackage.INTERFIX_LEXICAL: return createInterfixLexical();
case EgyDslPackage.INTERFIX_FLEXION: return createInterfixFlexion();
case EgyDslPackage.INTERFIX_SUFFIX_PRONOM_LEXICAL: return createInterfixSuffixPronomLexical();
case EgyDslPackage.INTERFIX_PREFIX_NON_LEXICAL: return createInterfixPrefixNonLexical();
case EgyDslPackage.INTERFIX_PREFIX_LEXICAL: return createInterfixPrefixLexical();
case EgyDslPackage.INTERFIX_CONNECTION_SYLLABIC_GROUP: return createInterfixConnectionSyllabicGroup();
case EgyDslPackage.INTERFIX_COMPOUND_WORDS: return createInterfixCompoundWords();
case EgyDslPackage.INTERFIX_PHONETICAL_COMPLEMENT: return createInterfixPhoneticalComplement();
case EgyDslPackage.VERS_MARKER: return createVersMarker();
case EgyDslPackage.EMENDATION_VERS_MARKER: return createEmendationVersMarker();
case EgyDslPackage.DISPUTABLE_VERS_MARKER: return createDisputableVersMarker();
case EgyDslPackage.DELETED_VERS_MARKER: return createDeletedVersMarker();
case EgyDslPackage.DESTROYED_VERS_MARKER: return createDestroyedVersMarker();
case EgyDslPackage.DESTROYED_VERS_FRONTIER_MARKER: return createDestroyedVersFrontierMarker();
case EgyDslPackage.PARTIAL_DESTROYED_VERS_MARKER: return createPartialDestroyedVersMarker();
case EgyDslPackage.MISSING_VERS_MARKER: return createMissingVersMarker();
case EgyDslPackage.RESTORATION_OVER_RASUR_MARKER: return createRestorationOverRasurMarker();
case EgyDslPackage.ANCIENT_EXPANDED_MARKER: return createAncientExpandedMarker();
case EgyDslPackage.RASUR_MARKER: return createRasurMarker();
case EgyDslPackage.VERS_FRONTIER_MARKER: return createVersFrontierMarker();
case EgyDslPackage.VERSBREAK_MARKER: return createVersbreakMarker();
case EgyDslPackage.BROKEN_VERSBREAK_MARKER: return createBrokenVersbreakMarker();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TextContent createTextContent()
{
TextContentImpl textContent = new TextContentImpl();
return textContent;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TextItem createTextItem()
{
TextItemImpl textItem = new TextItemImpl();
return textItem;
}
/**
* <!-- begin-user-doc -->
<SUF>*/
public Sentence createSentence()
{
SentenceImpl sentence = new SentenceImpl();
return sentence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SentenceItem createSentenceItem()
{
SentenceItemImpl sentenceItem = new SentenceItemImpl();
return sentenceItem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AbstractMarker createAbstractMarker()
{
AbstractMarkerImpl abstractMarker = new AbstractMarkerImpl();
return abstractMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Ambivalence createAmbivalence()
{
AmbivalenceImpl ambivalence = new AmbivalenceImpl();
return ambivalence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Case createCase()
{
CaseImpl case_ = new CaseImpl();
return case_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SentenceItemNoAmbivalence createSentenceItemNoAmbivalence()
{
SentenceItemNoAmbivalenceImpl sentenceItemNoAmbivalence = new SentenceItemNoAmbivalenceImpl();
return sentenceItemNoAmbivalence;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Marker createMarker()
{
MarkerImpl marker = new MarkerImpl();
return marker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestructionMarker createDestructionMarker()
{
DestructionMarkerImpl destructionMarker = new DestructionMarkerImpl();
return destructionMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Word createWord()
{
WordImpl word = new WordImpl();
return word;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WordPart createWordPart()
{
WordPartImpl wordPart = new WordPartImpl();
return wordPart;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WordMiddle createWordMiddle()
{
WordMiddleImpl wordMiddle = new WordMiddleImpl();
return wordMiddle;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Chars createChars()
{
CharsImpl chars = new CharsImpl();
return chars;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Brackets createBrackets()
{
BracketsImpl brackets = new BracketsImpl();
return brackets;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Oval createOval()
{
OvalImpl oval = new OvalImpl();
return oval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Serech createSerech()
{
SerechImpl serech = new SerechImpl();
return serech;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Cartouche createCartouche()
{
CartoucheImpl cartouche = new CartoucheImpl();
return cartouche;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoCartouche createNoCartouche()
{
NoCartoucheImpl noCartouche = new NoCartoucheImpl();
return noCartouche;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Expanded createExpanded()
{
ExpandedImpl expanded = new ExpandedImpl();
return expanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AncientExpanded createAncientExpanded()
{
AncientExpandedImpl ancientExpanded = new AncientExpandedImpl();
return ancientExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoExpanded createNoExpanded()
{
NoExpandedImpl noExpanded = new NoExpandedImpl();
return noExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Emendation createEmendation()
{
EmendationImpl emendation = new EmendationImpl();
return emendation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoEmendation createNoEmendation()
{
NoEmendationImpl noEmendation = new NoEmendationImpl();
return noEmendation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisputableReading createDisputableReading()
{
DisputableReadingImpl disputableReading = new DisputableReadingImpl();
return disputableReading;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoDisputableReading createNoDisputableReading()
{
NoDisputableReadingImpl noDisputableReading = new NoDisputableReadingImpl();
return noDisputableReading;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Lacuna createLacuna()
{
LacunaImpl lacuna = new LacunaImpl();
return lacuna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoLacuna createNoLacuna()
{
NoLacunaImpl noLacuna = new NoLacunaImpl();
return noLacuna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Deletion createDeletion()
{
DeletionImpl deletion = new DeletionImpl();
return deletion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoDeletion createNoDeletion()
{
NoDeletionImpl noDeletion = new NoDeletionImpl();
return noDeletion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ExpandedColumn createExpandedColumn()
{
ExpandedColumnImpl expandedColumn = new ExpandedColumnImpl();
return expandedColumn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoExpandedColumn createNoExpandedColumn()
{
NoExpandedColumnImpl noExpandedColumn = new NoExpandedColumnImpl();
return noExpandedColumn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Rasur createRasur()
{
RasurImpl rasur = new RasurImpl();
return rasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoRasur createNoRasur()
{
NoRasurImpl noRasur = new NoRasurImpl();
return noRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoAncientExpanded createNoAncientExpanded()
{
NoAncientExpandedImpl noAncientExpanded = new NoAncientExpandedImpl();
return noAncientExpanded;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RestorationOverRasur createRestorationOverRasur()
{
RestorationOverRasurImpl restorationOverRasur = new RestorationOverRasurImpl();
return restorationOverRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoRestorationOverRasur createNoRestorationOverRasur()
{
NoRestorationOverRasurImpl noRestorationOverRasur = new NoRestorationOverRasurImpl();
return noRestorationOverRasur;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PartialDestruction createPartialDestruction()
{
PartialDestructionImpl partialDestruction = new PartialDestructionImpl();
return partialDestruction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NoPartialDestruction createNoPartialDestruction()
{
NoPartialDestructionImpl noPartialDestruction = new NoPartialDestructionImpl();
return noPartialDestruction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Interfix createInterfix()
{
InterfixImpl interfix = new InterfixImpl();
return interfix;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixLexical createInterfixLexical()
{
InterfixLexicalImpl interfixLexical = new InterfixLexicalImpl();
return interfixLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixFlexion createInterfixFlexion()
{
InterfixFlexionImpl interfixFlexion = new InterfixFlexionImpl();
return interfixFlexion;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixSuffixPronomLexical createInterfixSuffixPronomLexical()
{
InterfixSuffixPronomLexicalImpl interfixSuffixPronomLexical = new InterfixSuffixPronomLexicalImpl();
return interfixSuffixPronomLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPrefixNonLexical createInterfixPrefixNonLexical()
{
InterfixPrefixNonLexicalImpl interfixPrefixNonLexical = new InterfixPrefixNonLexicalImpl();
return interfixPrefixNonLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPrefixLexical createInterfixPrefixLexical()
{
InterfixPrefixLexicalImpl interfixPrefixLexical = new InterfixPrefixLexicalImpl();
return interfixPrefixLexical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixConnectionSyllabicGroup createInterfixConnectionSyllabicGroup()
{
InterfixConnectionSyllabicGroupImpl interfixConnectionSyllabicGroup = new InterfixConnectionSyllabicGroupImpl();
return interfixConnectionSyllabicGroup;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixCompoundWords createInterfixCompoundWords()
{
InterfixCompoundWordsImpl interfixCompoundWords = new InterfixCompoundWordsImpl();
return interfixCompoundWords;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InterfixPhoneticalComplement createInterfixPhoneticalComplement()
{
InterfixPhoneticalComplementImpl interfixPhoneticalComplement = new InterfixPhoneticalComplementImpl();
return interfixPhoneticalComplement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersMarker createVersMarker()
{
VersMarkerImpl versMarker = new VersMarkerImpl();
return versMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EmendationVersMarker createEmendationVersMarker()
{
EmendationVersMarkerImpl emendationVersMarker = new EmendationVersMarkerImpl();
return emendationVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisputableVersMarker createDisputableVersMarker()
{
DisputableVersMarkerImpl disputableVersMarker = new DisputableVersMarkerImpl();
return disputableVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DeletedVersMarker createDeletedVersMarker()
{
DeletedVersMarkerImpl deletedVersMarker = new DeletedVersMarkerImpl();
return deletedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestroyedVersMarker createDestroyedVersMarker()
{
DestroyedVersMarkerImpl destroyedVersMarker = new DestroyedVersMarkerImpl();
return destroyedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DestroyedVersFrontierMarker createDestroyedVersFrontierMarker()
{
DestroyedVersFrontierMarkerImpl destroyedVersFrontierMarker = new DestroyedVersFrontierMarkerImpl();
return destroyedVersFrontierMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PartialDestroyedVersMarker createPartialDestroyedVersMarker()
{
PartialDestroyedVersMarkerImpl partialDestroyedVersMarker = new PartialDestroyedVersMarkerImpl();
return partialDestroyedVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MissingVersMarker createMissingVersMarker()
{
MissingVersMarkerImpl missingVersMarker = new MissingVersMarkerImpl();
return missingVersMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RestorationOverRasurMarker createRestorationOverRasurMarker()
{
RestorationOverRasurMarkerImpl restorationOverRasurMarker = new RestorationOverRasurMarkerImpl();
return restorationOverRasurMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AncientExpandedMarker createAncientExpandedMarker()
{
AncientExpandedMarkerImpl ancientExpandedMarker = new AncientExpandedMarkerImpl();
return ancientExpandedMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RasurMarker createRasurMarker()
{
RasurMarkerImpl rasurMarker = new RasurMarkerImpl();
return rasurMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersFrontierMarker createVersFrontierMarker()
{
VersFrontierMarkerImpl versFrontierMarker = new VersFrontierMarkerImpl();
return versFrontierMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VersbreakMarker createVersbreakMarker()
{
VersbreakMarkerImpl versbreakMarker = new VersbreakMarkerImpl();
return versbreakMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BrokenVersbreakMarker createBrokenVersbreakMarker()
{
BrokenVersbreakMarkerImpl brokenVersbreakMarker = new BrokenVersbreakMarkerImpl();
return brokenVersbreakMarker;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EgyDslPackage getEgyDslPackage()
{
return (EgyDslPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static EgyDslPackage getPackage()
{
return EgyDslPackage.eINSTANCE;
}
} //EgyDslFactoryImpl
|
204358_2 | package ch.bfh.bti7081.model;
import ch.bfh.bti7081.model.dossier.DossierQuerier;
import ch.bfh.bti7081.model.entities.*;
import ch.bfh.bti7081.model.patient.PatientQuerier;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
/**
* Used to generate dummy data.
* This class is only used to provide a greenfield for all developer, so they all can work with the same data.
*
* @author [email protected]
*/
class DataGenerator {
private static UnitOfWork unitOfWork = new UnitOfWork(DbConnector.getDatabase());
/**
* Purges all content of the used database to provide a greenfield.
*/
private static void purgeAll(){
// Delete all doctors in DB
System.out.println("[*] Going to delete all doctors in db...");
DataGenerator.unitOfWork.getDoctorRepo().getAll().forEach(x -> unitOfWork.getDoctorRepo().delete(x));
System.out.println("[+] Doctors have been deleted");
System.out.println("[*] Going to delete all patients in db...");
DataGenerator.unitOfWork.getPatientRepo().getAll().forEach(x -> unitOfWork.getPatientRepo().delete(x));
System.out.println("[+] Patients have been deleted");
System.out.println("[*] Going to delete all dossiers in db...");
DataGenerator.unitOfWork.getDossierRepo().getAll().forEach(x -> unitOfWork.getDossierRepo().delete(x));
System.out.println("[+] Dossiers have been deleted");
System.out.println("[*] Going to delete all reports in db...");
DataGenerator.unitOfWork.getReportRepo().getAll().forEach(x -> unitOfWork.getReportRepo().delete(x));
System.out.println("[+] Reports have been deleted");
System.out.println("[*] Going to delete all messages in db...");
DataGenerator.unitOfWork.getMessageRepo().getAll().forEach(x -> unitOfWork.getMessageRepo().delete(x));
System.out.println("[+] Messages have been deleted");
System.out.println("[*] Going to delete all objectives in db...");
DataGenerator.unitOfWork.getObjectiveRepo().getAll().forEach(x -> unitOfWork.getObjectiveRepo().delete(x));
System.out.println("[+] Messages have been deleted");
// Make changes valid
unitOfWork.commit();
}
/**
* Generates doctor dummy data
*/
private static void generateDoctors(){
System.out.println("[*] Going to create all doctors...");
List<Doctor> doctors = new ArrayList<>();
doctors.add(new Doctor("Albert", "Amman",new ArrayList<>() ));
doctors.add(new Doctor("Peter", "Petersen", new ArrayList<>()));
doctors.add(new Doctor("Hans", "Horst", new ArrayList<>()));
unitOfWork.getDoctorRepo().setAll(doctors);
unitOfWork.commit();
System.out.println("[+] Doctors have been committed");
}
/**
* Generates patient dummy data as well as the corresponding dossiers
*/
private static void generatePatients(){
List<Patient> patients = new ArrayList<>();
patients.add(new Patient("Robert", "Pfeiffer"));
patients.add(new Patient("Stefan", "Precht"));
patients.add(new Patient("Alfred", "Ploch"));
patients.add(new Patient("Kevin", "Riesen"));
patients.add(new Patient("Gian", "Demarmels"));
patients.add(new Patient("Yannis", "Schmutz"));
patients.add(new Patient("Lars", "Peyer"));
patients.add(new Patient("Adrian", "Berger"));
patients.add(new Patient("Matthias", "Ossola"));
unitOfWork.getPatientRepo().setAll(patients);
unitOfWork.commit();
List<Dossier> dossiers = new ArrayList<>();
unitOfWork.getPatientRepo().getAll().forEach(x -> {
Dossier dossier = new Dossier();
dossier.setId(ObjectId.get());
dossier.setPatientId(x.getId());
dossiers.add(dossier);
x.setDossierId(dossier.getId());
unitOfWork.getPatientRepo().update(x);
});
unitOfWork.getDossierRepo().setAll(dossiers);
unitOfWork.commit();
}
/**
* Generates patient dummy data as well as the corresponding dossiers
*/
private static void generateObjectives(){
List<Objective> objectives = new ArrayList<>();
List<Patient> patients = unitOfWork.getPatientRepo().getAll();
List<Doctor> doctors = unitOfWork.getDoctorRepo().getAll();
patients.forEach(x -> {
objectives.add(new Objective(
new Date(),
doctors.get(0).getId(),
x.getId(),
"Do not longer take drugs like a 18 year old girl on a Justin Bieber concert.",
"No more drugs",
3,
2,
null
));
objectives.add(new Objective(
new Date(),
doctors.get(1).getId(),
x.getId(),
"Elephants can drink up to 200 liters of water a day. Become 1% of an elephant and drink 2 liter a day.",
"Drink water",
3,
0,
null
));
});
unitOfWork.getObjectiveRepo().setAll(objectives);
unitOfWork.commit();
}
/**
* Assigns the already existing patients to doctors
*/
private static void assignPatientsToDoctors(){
List<Patient> patients = unitOfWork.getPatientRepo().getAll();
List<Doctor> doctors = unitOfWork.getDoctorRepo().getAll();
ListIterator<Patient> patientListIterator = patients.listIterator();
Integer doctorListSize = doctors.size();
while (patientListIterator.hasNext()){
Patient patient = patientListIterator.next();
doctors.get(patientListIterator.nextIndex() % doctorListSize).addPatient(patient);
// Assign the patient to two doctors if more than one doctor is defined
// This assignment will be relevant in order to notify at least one doctor for a given message
if(doctorListSize > 1){
doctors.get((patientListIterator.nextIndex() + 1) % doctorListSize).addPatient(patient);
}
}
unitOfWork.getDoctorRepo().updateMany(doctors);
unitOfWork.commit();
}
/**
* Generates report dummy data
*/
private static void generateReports(){
List<Report> reports = new ArrayList<>();
unitOfWork.getDossierRepo().getAll().forEach(x ->{
reports.add(new Report("Some content", x.getId()));
reports.add(new Report("Some further content", x.getId()));
});
unitOfWork.getReportRepo().setAll(reports);
unitOfWork.commit();
}
/**
* Generates message dummy data
*
* for every doctor:
* for every one of doctor's patients:
* get patient's dossier
* for every report in dossier
* add one message for this report, written by a specific doctor
*/
private static void generateMessages(){
List<Message> messages = new ArrayList<>();
PatientQuerier patientQuerier = new PatientQuerier();
DossierQuerier dossierQuerier = new DossierQuerier();
unitOfWork.getDoctorRepo().getAll().forEach(doctor -> {
doctor.getPatients().forEach(patientID -> {
dossierQuerier.getReports(patientQuerier.getDossier(patientID).getId(), 10).forEach(report -> {
messages.add(new Message("Hi guys", doctor.getId(), report.getId(), new Date()));
});
});
});
unitOfWork.getMessageRepo().setAll(messages);
unitOfWork.commit();
}
/**
*
* @param args System arguments, what else?
*/
public static void main(String[] args){
/*
Mongo Daemon has to be started using the "mongod" command in a terminal!
*/
// Todo: Implement a logger...
System.out.println("[*] Starting DataGenerator");
DataGenerator.purgeAll();
DataGenerator.generateDoctors();
DataGenerator.generatePatients();
DataGenerator.assignPatientsToDoctors();
DataGenerator.generateReports();
DataGenerator.generateMessages();
DataGenerator.generateObjectives();
System.out.println("[+] DataGenerator completed");
}
}
| thetractor/ch.bfh.bti7081.s2019.orange | src/main/java/ch/bfh/bti7081/model/DataGenerator.java | 2,425 | // Delete all doctors in DB | line_comment | nl | package ch.bfh.bti7081.model;
import ch.bfh.bti7081.model.dossier.DossierQuerier;
import ch.bfh.bti7081.model.entities.*;
import ch.bfh.bti7081.model.patient.PatientQuerier;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
/**
* Used to generate dummy data.
* This class is only used to provide a greenfield for all developer, so they all can work with the same data.
*
* @author [email protected]
*/
class DataGenerator {
private static UnitOfWork unitOfWork = new UnitOfWork(DbConnector.getDatabase());
/**
* Purges all content of the used database to provide a greenfield.
*/
private static void purgeAll(){
// Delete all<SUF>
System.out.println("[*] Going to delete all doctors in db...");
DataGenerator.unitOfWork.getDoctorRepo().getAll().forEach(x -> unitOfWork.getDoctorRepo().delete(x));
System.out.println("[+] Doctors have been deleted");
System.out.println("[*] Going to delete all patients in db...");
DataGenerator.unitOfWork.getPatientRepo().getAll().forEach(x -> unitOfWork.getPatientRepo().delete(x));
System.out.println("[+] Patients have been deleted");
System.out.println("[*] Going to delete all dossiers in db...");
DataGenerator.unitOfWork.getDossierRepo().getAll().forEach(x -> unitOfWork.getDossierRepo().delete(x));
System.out.println("[+] Dossiers have been deleted");
System.out.println("[*] Going to delete all reports in db...");
DataGenerator.unitOfWork.getReportRepo().getAll().forEach(x -> unitOfWork.getReportRepo().delete(x));
System.out.println("[+] Reports have been deleted");
System.out.println("[*] Going to delete all messages in db...");
DataGenerator.unitOfWork.getMessageRepo().getAll().forEach(x -> unitOfWork.getMessageRepo().delete(x));
System.out.println("[+] Messages have been deleted");
System.out.println("[*] Going to delete all objectives in db...");
DataGenerator.unitOfWork.getObjectiveRepo().getAll().forEach(x -> unitOfWork.getObjectiveRepo().delete(x));
System.out.println("[+] Messages have been deleted");
// Make changes valid
unitOfWork.commit();
}
/**
* Generates doctor dummy data
*/
private static void generateDoctors(){
System.out.println("[*] Going to create all doctors...");
List<Doctor> doctors = new ArrayList<>();
doctors.add(new Doctor("Albert", "Amman",new ArrayList<>() ));
doctors.add(new Doctor("Peter", "Petersen", new ArrayList<>()));
doctors.add(new Doctor("Hans", "Horst", new ArrayList<>()));
unitOfWork.getDoctorRepo().setAll(doctors);
unitOfWork.commit();
System.out.println("[+] Doctors have been committed");
}
/**
* Generates patient dummy data as well as the corresponding dossiers
*/
private static void generatePatients(){
List<Patient> patients = new ArrayList<>();
patients.add(new Patient("Robert", "Pfeiffer"));
patients.add(new Patient("Stefan", "Precht"));
patients.add(new Patient("Alfred", "Ploch"));
patients.add(new Patient("Kevin", "Riesen"));
patients.add(new Patient("Gian", "Demarmels"));
patients.add(new Patient("Yannis", "Schmutz"));
patients.add(new Patient("Lars", "Peyer"));
patients.add(new Patient("Adrian", "Berger"));
patients.add(new Patient("Matthias", "Ossola"));
unitOfWork.getPatientRepo().setAll(patients);
unitOfWork.commit();
List<Dossier> dossiers = new ArrayList<>();
unitOfWork.getPatientRepo().getAll().forEach(x -> {
Dossier dossier = new Dossier();
dossier.setId(ObjectId.get());
dossier.setPatientId(x.getId());
dossiers.add(dossier);
x.setDossierId(dossier.getId());
unitOfWork.getPatientRepo().update(x);
});
unitOfWork.getDossierRepo().setAll(dossiers);
unitOfWork.commit();
}
/**
* Generates patient dummy data as well as the corresponding dossiers
*/
private static void generateObjectives(){
List<Objective> objectives = new ArrayList<>();
List<Patient> patients = unitOfWork.getPatientRepo().getAll();
List<Doctor> doctors = unitOfWork.getDoctorRepo().getAll();
patients.forEach(x -> {
objectives.add(new Objective(
new Date(),
doctors.get(0).getId(),
x.getId(),
"Do not longer take drugs like a 18 year old girl on a Justin Bieber concert.",
"No more drugs",
3,
2,
null
));
objectives.add(new Objective(
new Date(),
doctors.get(1).getId(),
x.getId(),
"Elephants can drink up to 200 liters of water a day. Become 1% of an elephant and drink 2 liter a day.",
"Drink water",
3,
0,
null
));
});
unitOfWork.getObjectiveRepo().setAll(objectives);
unitOfWork.commit();
}
/**
* Assigns the already existing patients to doctors
*/
private static void assignPatientsToDoctors(){
List<Patient> patients = unitOfWork.getPatientRepo().getAll();
List<Doctor> doctors = unitOfWork.getDoctorRepo().getAll();
ListIterator<Patient> patientListIterator = patients.listIterator();
Integer doctorListSize = doctors.size();
while (patientListIterator.hasNext()){
Patient patient = patientListIterator.next();
doctors.get(patientListIterator.nextIndex() % doctorListSize).addPatient(patient);
// Assign the patient to two doctors if more than one doctor is defined
// This assignment will be relevant in order to notify at least one doctor for a given message
if(doctorListSize > 1){
doctors.get((patientListIterator.nextIndex() + 1) % doctorListSize).addPatient(patient);
}
}
unitOfWork.getDoctorRepo().updateMany(doctors);
unitOfWork.commit();
}
/**
* Generates report dummy data
*/
private static void generateReports(){
List<Report> reports = new ArrayList<>();
unitOfWork.getDossierRepo().getAll().forEach(x ->{
reports.add(new Report("Some content", x.getId()));
reports.add(new Report("Some further content", x.getId()));
});
unitOfWork.getReportRepo().setAll(reports);
unitOfWork.commit();
}
/**
* Generates message dummy data
*
* for every doctor:
* for every one of doctor's patients:
* get patient's dossier
* for every report in dossier
* add one message for this report, written by a specific doctor
*/
private static void generateMessages(){
List<Message> messages = new ArrayList<>();
PatientQuerier patientQuerier = new PatientQuerier();
DossierQuerier dossierQuerier = new DossierQuerier();
unitOfWork.getDoctorRepo().getAll().forEach(doctor -> {
doctor.getPatients().forEach(patientID -> {
dossierQuerier.getReports(patientQuerier.getDossier(patientID).getId(), 10).forEach(report -> {
messages.add(new Message("Hi guys", doctor.getId(), report.getId(), new Date()));
});
});
});
unitOfWork.getMessageRepo().setAll(messages);
unitOfWork.commit();
}
/**
*
* @param args System arguments, what else?
*/
public static void main(String[] args){
/*
Mongo Daemon has to be started using the "mongod" command in a terminal!
*/
// Todo: Implement a logger...
System.out.println("[*] Starting DataGenerator");
DataGenerator.purgeAll();
DataGenerator.generateDoctors();
DataGenerator.generatePatients();
DataGenerator.assignPatientsToDoctors();
DataGenerator.generateReports();
DataGenerator.generateMessages();
DataGenerator.generateObjectives();
System.out.println("[+] DataGenerator completed");
}
}
|
201646_28 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.recording.jibri;
import org.jitsi.xmpp.extensions.jibri.*;
import org.jitsi.xmpp.extensions.jibri.JibriIq.*;
import net.java.sip.communicator.service.protocol.*;
import org.jetbrains.annotations.*;
import org.jitsi.eventadmin.*;
import org.jitsi.jicofo.*;
import org.jitsi.osgi.*;
import org.jitsi.protocol.xmpp.*;
import org.jitsi.utils.logging.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jxmpp.jid.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Class holds the information about Jibri session. It can be either live
* streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic
* which is supposed to try another instance when the current one fails. To make
* this happen it needs to cache all the information required to start new
* session. It uses {@link JibriDetector} to select new Jibri.
*
* @author Pawel Domas
*/
public class JibriSession
{
/**
* The class logger which can be used to override logging level inherited
* from {@link JitsiMeetConference}.
*/
static private final Logger classLogger
= Logger.getLogger(JibriSession.class);
/**
* Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in
* the middle of starting of the recording process.
*/
static private boolean isStartingStatus(JibriIq.Status status)
{
return JibriIq.Status.PENDING.equals(status);
}
/**
* The JID of the Jibri currently being used by this session or
* <tt>null</tt> otherwise.
*/
private Jid currentJibriJid;
/**
* The display name Jibri attribute received from Jitsi Meet to be passed
* further to Jibri instance that will be used.
*/
private final String displayName;
/**
* Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for
* regular Jibri (<tt>false</tt>).
*/
private final boolean isSIP;
/**
* {@link JibriDetector} instance used to select a Jibri which will be used
* by this session.
*/
private final JibriDetector jibriDetector;
/**
* Helper class that registers for {@link JibriEvent}s in the OSGi context
* obtained from the {@link FocusBundleActivator}.
*/
private final JibriEventHandler jibriEventHandler = new JibriEventHandler();
/**
* Current Jibri recording status.
*/
private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED;
/**
* The logger for this instance. Uses the logging level either of the
* {@link #classLogger} or {@link JitsiMeetConference#getLogger()}
* whichever is higher.
*/
private final Logger logger;
/**
* The owner which will be notified about status changes of this session.
*/
private final Owner owner;
/**
* Reference to scheduled {@link PendingStatusTimeout}
*/
private ScheduledFuture<?> pendingTimeoutTask;
/**
* How long this session can stay in "pending" status, before retry is made
* (given in seconds).
*/
private final long pendingTimeout;
/**
* The (bare) JID of the MUC room.
*/
private final EntityBareJid roomName;
/**
* Executor service for used to schedule pending timeout tasks.
*/
private final ScheduledExecutorService scheduledExecutor;
/**
* The SIP address attribute received from Jitsi Meet which is to be used to
* start a SIP call. This field's used only if {@link #isSIP} is set to
* <tt>true</tt>.
*/
private final String sipAddress;
/**
* The id of the live stream received from Jitsi Meet, which will be used to
* start live streaming session (used only if {@link #isSIP is set to
* <tt>true</tt>}.
*/
private final String streamID;
private final String sessionId;
/**
* The broadcast id of the YouTube broadcast, if available. This is used
* to generate and distribute the viewing url of the live stream
*/
private final String youTubeBroadcastId;
/**
* A JSON-encoded string containing arbitrary application data for Jibri
*/
private final String applicationData;
/**
* {@link XmppConnection} instance used to send/listen for XMPP packets.
*/
private final XmppConnection xmpp;
/**
* The maximum amount of retries we'll attempt
*/
private final int maxNumRetries;
/**
* How many times we've retried this request to another Jibri
*/
private int numRetries = 0;
/**
* The full JID of the entity that has initiated the recording flow.
*/
private Jid initiator;
/**
* The full JID of the entity that has initiated the stop of the recording.
*/
private Jid terminator;
/**
* Creates new {@link JibriSession} instance.
* @param owner the session owner which will be notified about this session
* state changes.
* @param roomName the name if the XMPP MUC room (full address).
* @param pendingTimeout how many seconds this session can wait in pending
* state, before trying another Jibri instance or failing with an error.
* @param connection the XMPP connection which will be used to send/listen
* for packets.
* @param scheduledExecutor the executor service which will be used to
* schedule pending timeout task execution.
* @param jibriDetector the Jibri detector which will be used to select
* Jibri instance.
* @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for
* a regular live streaming Jibri type of session.
* @param sipAddress a SIP address if it's a SIP session
* @param displayName a display name to be used by Jibri participant
* entering the conference once the session starts.
* @param streamID a live streaming ID if it's not a SIP session
* @param youTubeBroadcastId the YouTube broadcast id (optional)
* @param applicationData a JSON-encoded string containing application-specific
* data for Jibri
* @param logLevelDelegate logging level delegate which will be used to
* select logging level for this instance {@link #logger}.
*/
JibriSession(
JibriSession.Owner owner,
EntityBareJid roomName,
Jid initiator,
long pendingTimeout,
int maxNumRetries,
XmppConnection connection,
ScheduledExecutorService scheduledExecutor,
JibriDetector jibriDetector,
boolean isSIP,
String sipAddress,
String displayName,
String streamID,
String youTubeBroadcastId,
String sessionId,
String applicationData,
Logger logLevelDelegate)
{
this.owner = owner;
this.roomName = roomName;
this.initiator = initiator;
this.scheduledExecutor
= Objects.requireNonNull(scheduledExecutor, "scheduledExecutor");
this.pendingTimeout = pendingTimeout;
this.maxNumRetries = maxNumRetries;
this.isSIP = isSIP;
this.jibriDetector = jibriDetector;
this.sipAddress = sipAddress;
this.displayName = displayName;
this.streamID = streamID;
this.youTubeBroadcastId = youTubeBroadcastId;
this.sessionId = sessionId;
this.applicationData = applicationData;
this.xmpp = connection;
logger = Logger.getLogger(classLogger, logLevelDelegate);
}
/**
* Starts this session. A new Jibri instance will be selected and start
* request will be sent (in non blocking mode).
* @return true if the start is successful, false otherwise
*/
synchronized public boolean start()
{
final Jid jibriJid = jibriDetector.selectJibri();
if (jibriJid != null)
{
try
{
jibriEventHandler.start(FocusBundleActivator.bundleContext);
sendJibriStartIq(jibriJid);
logger.info("Starting session with Jibri " + jibriJid);
return true;
}
catch (Exception e)
{
logger.error("Failed to start Jibri event handler: " + e, e);
}
}
else
{
logger.error("Unable to find an available Jibri, can't start");
}
return false;
}
/**
* Stops this session if it's not already stopped.
* @param initiator The jid of the initiator of the stop request.
*/
synchronized public void stop(Jid initiator)
{
if (currentJibriJid == null)
{
return;
}
this.terminator = initiator;
JibriIq stopRequest = new JibriIq();
stopRequest.setType(IQ.Type.set);
stopRequest.setTo(currentJibriJid);
stopRequest.setAction(JibriIq.Action.STOP);
logger.info("Trying to stop: " + stopRequest.toXML());
// When we send stop, we won't get an OFF presence back (just
// a response to this message) so clean up the session
// in the processing of the response.
try
{
xmpp.sendIqWithResponseCallback(
stopRequest,
stanza -> {
JibriIq resp = (JibriIq)stanza;
processJibriIqFromJibri(resp);
},
exception -> {
logger.error(
"Error sending stop iq: " + exception.toString());
},
60000);
} catch (SmackException.NotConnectedException | InterruptedException e)
{
logger.error("Error sending stop iq: " + e.toString());
}
}
private void cleanupSession()
{
logger.info("Cleaning up current JibriSession");
currentJibriJid = null;
numRetries = 0;
try
{
jibriEventHandler.stop(FocusBundleActivator.bundleContext);
}
catch (Exception e)
{
logger.error("Failed to stop Jibri event handler: " + e, e);
}
}
/**
* Accept only XMPP packets which are coming from the Jibri currently used
* by this session.
* {@inheritDoc}
*/
public boolean accept(JibriIq packet)
{
return currentJibriJid != null
&& (packet.getFrom().equals(currentJibriJid));
}
/**
* @return a string describing this session instance, used for logging
* purpose
*/
private String nickname()
{
return this.isSIP ? "SIP Jibri" : "Jibri";
}
/**
* Process a {@link JibriIq} *request* from Jibri
* @param request
* @return the response
*/
IQ processJibriIqRequestFromJibri(JibriIq request)
{
processJibriIqFromJibri(request);
return IQ.createResultIQ(request);
}
/**
* Process a {@link JibriIq} from Jibri (note that this
* may be an IQ request or an IQ response)
* @param iq
*/
private void processJibriIqFromJibri(JibriIq iq)
{
// We have something from Jibri - let's update recording status
JibriIq.Status status = iq.getStatus();
if (!JibriIq.Status.UNDEFINED.equals(status))
{
logger.info(
"Updating status from JIBRI: "
+ iq.toXML() + " for " + roomName);
handleJibriStatusUpdate(
iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry());
}
else
{
logger.error(
"Received UNDEFINED status from jibri: " + iq.toString());
}
}
/**
* Gets the recording mode of this jibri session
* @return the recording mode for this session (STREAM, FILE or UNDEFINED
* in the case that this isn't a recording session but actually a SIP
* session)
*/
JibriIq.RecordingMode getRecordingMode()
{
if (sipAddress != null)
{
return RecordingMode.UNDEFINED;
}
else if (streamID != null)
{
return RecordingMode.STREAM;
}
return RecordingMode.FILE;
}
/**
* Sends an IQ to the given Jibri instance and asks it to start
* recording/SIP call.
*/
private void sendJibriStartIq(final Jid jibriJid)
{
// Store Jibri JID to make the packet filter accept the response
currentJibriJid = jibriJid;
logger.info(
"Starting Jibri " + jibriJid
+ (isSIP
? ("for SIP address: " + sipAddress)
: (" for stream ID: " + streamID))
+ " in room: " + roomName);
final JibriIq startIq = new JibriIq();
startIq.setTo(jibriJid);
startIq.setType(IQ.Type.set);
startIq.setAction(JibriIq.Action.START);
startIq.setSessionId(this.sessionId);
logger.debug(
"Passing on jibri application data: " + this.applicationData);
startIq.setAppData(this.applicationData);
if (streamID != null)
{
startIq.setStreamId(streamID);
startIq.setRecordingMode(RecordingMode.STREAM);
if (youTubeBroadcastId != null) {
startIq.setYouTubeBroadcastId(youTubeBroadcastId);
}
}
else
{
startIq.setRecordingMode(RecordingMode.FILE);
}
startIq.setSipAddress(sipAddress);
startIq.setDisplayName(displayName);
// Insert name of the room into Jibri START IQ
startIq.setRoom(roomName);
// We will not wait forever for the Jibri to start. This method can be
// run multiple times on retry, so we want to restart the pending
// timeout each time.
reschedulePendingTimeout();
try
{
JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq);
processJibriIqFromJibri(result);
}
catch (OperationFailedException e)
{
logger.error("Error sending Jibri start IQ: " + e.toString());
}
}
/**
* Method schedules/reschedules {@link PendingStatusTimeout} which will
* clear recording state after
* {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}.
*/
private void reschedulePendingTimeout()
{
if (pendingTimeoutTask != null)
{
logger.info(
"Rescheduling pending timeout task for room: " + roomName);
pendingTimeoutTask.cancel(false);
}
if (pendingTimeout > 0)
{
pendingTimeoutTask
= scheduledExecutor.schedule(
new PendingStatusTimeout(),
pendingTimeout, TimeUnit.SECONDS);
}
}
/**
* Check whether or not we should retry the current request to another Jibri
* @return true if we've not exceeded the max amount of retries,
* false otherwise
*/
private boolean maxRetriesExceeded()
{
return (maxNumRetries >= 0 && numRetries >= maxNumRetries);
}
/**
* Retry the current request with another Jibri (if one is available)
* @return true if we were able to find another Jibri to retry the request
* with, false otherwise
*/
private boolean retryRequestWithAnotherJibri()
{
numRetries++;
return start();
}
/**
* Handle a Jibri status update (this could come from an IQ response, a new
* IQ from Jibri, an XMPP event, etc.).
* This will handle:
* 1) Retrying with a new Jibri in case of an error
* 2) Cleaning up the session when the Jibri session finished successfully
* (or there was an error but we have no more Jibris left to try)
* @param jibriJid the jid of the jibri for which this status update applies
* @param newStatus the jibri's new status
* @param failureReason the jibri's failure reason, if any (otherwise null)
* @param shouldRetryParam if {@code failureReason} is not null, shouldRetry
* denotes whether or not we should retry the same
* request with another Jibri
*/
private void handleJibriStatusUpdate(
@NotNull Jid jibriJid,
JibriIq.Status newStatus,
@Nullable JibriIq.FailureReason failureReason,
@Nullable Boolean shouldRetryParam)
{
jibriStatus = newStatus;
logger.info("Got Jibri status update: Jibri " + jibriJid
+ " has status " + newStatus
+ " and failure reason " + failureReason
+ ", current Jibri jid is " + currentJibriJid);
if (currentJibriJid == null)
{
logger.info("Current session has already been cleaned up, ignoring");
return;
}
if (jibriJid.compareTo(currentJibriJid) != 0)
{
logger.info("This status update is from " + jibriJid +
" but the current Jibri is " + currentJibriJid + ", ignoring");
return;
}
// First: if we're no longer pending (regardless of the Jibri's
// new state), make sure we stop the pending timeout task
if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus))
{
logger.info(
"Jibri is no longer pending, cancelling pending timeout task");
pendingTimeoutTask.cancel(false);
pendingTimeoutTask = null;
}
// Now, if there was a failure of any kind we'll try and find another
// Jibri to keep things going
if (failureReason != null)
{
boolean shouldRetry;
if (shouldRetryParam == null)
{
logger.warn("failureReason was non-null but shouldRetry " +
"wasn't set, will NOT retry");
shouldRetry = false;
}
else
{
shouldRetry = shouldRetryParam;
}
// There was an error with the current Jibri, see if we should retry
if (shouldRetry && !maxRetriesExceeded())
{
logger.info("Jibri failed, trying to fall back to another Jibri");
if (retryRequestWithAnotherJibri())
{
// The fallback to another Jibri succeeded.
logger.info("Successfully resumed session with another Jibri");
}
else
{
logger.info("Failed to fall back to another Jibri, this "
+ "session has now failed");
// Propagate up that the session has failed entirely.
// We'll pass the original failure reason.
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
}
else
{
if (!shouldRetry)
{
logger.info("Jibri failed and signaled that we " +
"should not retry the same request");
}
else
{
// The Jibri we tried failed and we've reached the maxmium
// amount of retries we've been configured to attempt, so we'll
// give up trying to handle this request.
logger.info("Jibri failed, but max amount of retries ("
+ maxNumRetries + ") reached, giving up");
}
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
}
else if (Status.OFF.equals(newStatus))
{
logger.info("Jibri session ended cleanly, notifying owner and "
+ "cleaning up session");
// The Jibri stopped for some non-error reason
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
else if (Status.ON.equals(newStatus))
{
logger.info("Jibri session started, notifying owner");
// The Jibri stopped for some non-error reason
owner.onSessionStateChanged(this, newStatus, failureReason);
}
}
/**
* @return SIP address received from Jitsi Meet, which is used for SIP
* gateway session (makes sense only for SIP sessions).
*/
String getSipAddress()
{
return sipAddress;
}
/**
* Get the unique ID for this session. This is used to uniquely
* identify a Jibri session instance, even of the same type (meaning,
* for example, that two file recordings would have different session
* IDs). It will be passed to Jibri and Jibri will put the session ID
* in its presence, so the Jibri user for a particular session can
* be identified by the clients.
* @return the session ID
*/
public String getSessionId()
{
return this.sessionId;
}
/**
* Helper class handles registration for the {@link JibriEvent}s.
*/
private class JibriEventHandler
extends EventHandlerActivator
{
private JibriEventHandler()
{
super(new String[]{
JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE});
}
@Override
public void handleEvent(Event event)
{
if (!JibriEvent.isJibriEvent(event))
{
logger.error("Invalid event: " + event);
return;
}
final JibriEvent jibriEvent = (JibriEvent) event;
final String topic = jibriEvent.getTopic();
final Jid jibriJid = jibriEvent.getJibriJid();
synchronized (JibriSession.this)
{
if (JibriEvent.WENT_OFFLINE.equals(topic)
&& jibriJid.equals(currentJibriJid))
{
logger.error(
nickname() + " went offline: " + jibriJid
+ " for room: " + roomName);
handleJibriStatusUpdate(
jibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* Task scheduled after we have received RESULT response from Jibri and
* entered PENDING state. Will abort the recording if we do not transit to
* ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}
* limit is exceeded.
*/
private class PendingStatusTimeout implements Runnable
{
public void run()
{
synchronized (JibriSession.this)
{
// Clear this task reference, so it won't be
// cancelling itself on status change from PENDING
pendingTimeoutTask = null;
if (isStartingStatus(jibriStatus))
{
logger.error(
nickname() + " pending timeout! " + roomName);
// If a Jibri times out during the pending phase, it's
// likely hung or having some issue. We'll send a stop (so
// if/when it does 'recover', it knows to stop) and simulate
// an error status (like we do in
// JibriEventHandler#handleEvent when a Jibri goes offline)
// to trigger the fallback logic.
stop(null);
handleJibriStatusUpdate(
currentJibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* The JID of the entity that has initiated the recording flow.
* @return The JID of the entity that has initiated the recording flow.
*/
public Jid getInitiator()
{
return initiator;
}
/**
* The JID of the entity that has initiated the stop of the recording.
* @return The JID of the entity that has stopped the recording.
*/
public Jid getTerminator()
{
return terminator;
}
/**
* Interface instance passed to {@link JibriSession} constructor which
* specifies the session owner which will be notified about any status
* changes.
*/
public interface Owner
{
/**
* Called on {@link JibriSession} status update.
* @param jibriSession which status has changed
* @param newStatus the new status
* @param failureReason optional error for {@link JibriIq.Status#OFF}.
*/
void onSessionStateChanged(
JibriSession jibriSession,
JibriIq.Status newStatus,
JibriIq.FailureReason failureReason);
}
}
| theunafraid/jicofo | src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java | 7,112 | // When we send stop, we won't get an OFF presence back (just | line_comment | nl | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.recording.jibri;
import org.jitsi.xmpp.extensions.jibri.*;
import org.jitsi.xmpp.extensions.jibri.JibriIq.*;
import net.java.sip.communicator.service.protocol.*;
import org.jetbrains.annotations.*;
import org.jitsi.eventadmin.*;
import org.jitsi.jicofo.*;
import org.jitsi.osgi.*;
import org.jitsi.protocol.xmpp.*;
import org.jitsi.utils.logging.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jxmpp.jid.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Class holds the information about Jibri session. It can be either live
* streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic
* which is supposed to try another instance when the current one fails. To make
* this happen it needs to cache all the information required to start new
* session. It uses {@link JibriDetector} to select new Jibri.
*
* @author Pawel Domas
*/
public class JibriSession
{
/**
* The class logger which can be used to override logging level inherited
* from {@link JitsiMeetConference}.
*/
static private final Logger classLogger
= Logger.getLogger(JibriSession.class);
/**
* Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in
* the middle of starting of the recording process.
*/
static private boolean isStartingStatus(JibriIq.Status status)
{
return JibriIq.Status.PENDING.equals(status);
}
/**
* The JID of the Jibri currently being used by this session or
* <tt>null</tt> otherwise.
*/
private Jid currentJibriJid;
/**
* The display name Jibri attribute received from Jitsi Meet to be passed
* further to Jibri instance that will be used.
*/
private final String displayName;
/**
* Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for
* regular Jibri (<tt>false</tt>).
*/
private final boolean isSIP;
/**
* {@link JibriDetector} instance used to select a Jibri which will be used
* by this session.
*/
private final JibriDetector jibriDetector;
/**
* Helper class that registers for {@link JibriEvent}s in the OSGi context
* obtained from the {@link FocusBundleActivator}.
*/
private final JibriEventHandler jibriEventHandler = new JibriEventHandler();
/**
* Current Jibri recording status.
*/
private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED;
/**
* The logger for this instance. Uses the logging level either of the
* {@link #classLogger} or {@link JitsiMeetConference#getLogger()}
* whichever is higher.
*/
private final Logger logger;
/**
* The owner which will be notified about status changes of this session.
*/
private final Owner owner;
/**
* Reference to scheduled {@link PendingStatusTimeout}
*/
private ScheduledFuture<?> pendingTimeoutTask;
/**
* How long this session can stay in "pending" status, before retry is made
* (given in seconds).
*/
private final long pendingTimeout;
/**
* The (bare) JID of the MUC room.
*/
private final EntityBareJid roomName;
/**
* Executor service for used to schedule pending timeout tasks.
*/
private final ScheduledExecutorService scheduledExecutor;
/**
* The SIP address attribute received from Jitsi Meet which is to be used to
* start a SIP call. This field's used only if {@link #isSIP} is set to
* <tt>true</tt>.
*/
private final String sipAddress;
/**
* The id of the live stream received from Jitsi Meet, which will be used to
* start live streaming session (used only if {@link #isSIP is set to
* <tt>true</tt>}.
*/
private final String streamID;
private final String sessionId;
/**
* The broadcast id of the YouTube broadcast, if available. This is used
* to generate and distribute the viewing url of the live stream
*/
private final String youTubeBroadcastId;
/**
* A JSON-encoded string containing arbitrary application data for Jibri
*/
private final String applicationData;
/**
* {@link XmppConnection} instance used to send/listen for XMPP packets.
*/
private final XmppConnection xmpp;
/**
* The maximum amount of retries we'll attempt
*/
private final int maxNumRetries;
/**
* How many times we've retried this request to another Jibri
*/
private int numRetries = 0;
/**
* The full JID of the entity that has initiated the recording flow.
*/
private Jid initiator;
/**
* The full JID of the entity that has initiated the stop of the recording.
*/
private Jid terminator;
/**
* Creates new {@link JibriSession} instance.
* @param owner the session owner which will be notified about this session
* state changes.
* @param roomName the name if the XMPP MUC room (full address).
* @param pendingTimeout how many seconds this session can wait in pending
* state, before trying another Jibri instance or failing with an error.
* @param connection the XMPP connection which will be used to send/listen
* for packets.
* @param scheduledExecutor the executor service which will be used to
* schedule pending timeout task execution.
* @param jibriDetector the Jibri detector which will be used to select
* Jibri instance.
* @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for
* a regular live streaming Jibri type of session.
* @param sipAddress a SIP address if it's a SIP session
* @param displayName a display name to be used by Jibri participant
* entering the conference once the session starts.
* @param streamID a live streaming ID if it's not a SIP session
* @param youTubeBroadcastId the YouTube broadcast id (optional)
* @param applicationData a JSON-encoded string containing application-specific
* data for Jibri
* @param logLevelDelegate logging level delegate which will be used to
* select logging level for this instance {@link #logger}.
*/
JibriSession(
JibriSession.Owner owner,
EntityBareJid roomName,
Jid initiator,
long pendingTimeout,
int maxNumRetries,
XmppConnection connection,
ScheduledExecutorService scheduledExecutor,
JibriDetector jibriDetector,
boolean isSIP,
String sipAddress,
String displayName,
String streamID,
String youTubeBroadcastId,
String sessionId,
String applicationData,
Logger logLevelDelegate)
{
this.owner = owner;
this.roomName = roomName;
this.initiator = initiator;
this.scheduledExecutor
= Objects.requireNonNull(scheduledExecutor, "scheduledExecutor");
this.pendingTimeout = pendingTimeout;
this.maxNumRetries = maxNumRetries;
this.isSIP = isSIP;
this.jibriDetector = jibriDetector;
this.sipAddress = sipAddress;
this.displayName = displayName;
this.streamID = streamID;
this.youTubeBroadcastId = youTubeBroadcastId;
this.sessionId = sessionId;
this.applicationData = applicationData;
this.xmpp = connection;
logger = Logger.getLogger(classLogger, logLevelDelegate);
}
/**
* Starts this session. A new Jibri instance will be selected and start
* request will be sent (in non blocking mode).
* @return true if the start is successful, false otherwise
*/
synchronized public boolean start()
{
final Jid jibriJid = jibriDetector.selectJibri();
if (jibriJid != null)
{
try
{
jibriEventHandler.start(FocusBundleActivator.bundleContext);
sendJibriStartIq(jibriJid);
logger.info("Starting session with Jibri " + jibriJid);
return true;
}
catch (Exception e)
{
logger.error("Failed to start Jibri event handler: " + e, e);
}
}
else
{
logger.error("Unable to find an available Jibri, can't start");
}
return false;
}
/**
* Stops this session if it's not already stopped.
* @param initiator The jid of the initiator of the stop request.
*/
synchronized public void stop(Jid initiator)
{
if (currentJibriJid == null)
{
return;
}
this.terminator = initiator;
JibriIq stopRequest = new JibriIq();
stopRequest.setType(IQ.Type.set);
stopRequest.setTo(currentJibriJid);
stopRequest.setAction(JibriIq.Action.STOP);
logger.info("Trying to stop: " + stopRequest.toXML());
// When we<SUF>
// a response to this message) so clean up the session
// in the processing of the response.
try
{
xmpp.sendIqWithResponseCallback(
stopRequest,
stanza -> {
JibriIq resp = (JibriIq)stanza;
processJibriIqFromJibri(resp);
},
exception -> {
logger.error(
"Error sending stop iq: " + exception.toString());
},
60000);
} catch (SmackException.NotConnectedException | InterruptedException e)
{
logger.error("Error sending stop iq: " + e.toString());
}
}
private void cleanupSession()
{
logger.info("Cleaning up current JibriSession");
currentJibriJid = null;
numRetries = 0;
try
{
jibriEventHandler.stop(FocusBundleActivator.bundleContext);
}
catch (Exception e)
{
logger.error("Failed to stop Jibri event handler: " + e, e);
}
}
/**
* Accept only XMPP packets which are coming from the Jibri currently used
* by this session.
* {@inheritDoc}
*/
public boolean accept(JibriIq packet)
{
return currentJibriJid != null
&& (packet.getFrom().equals(currentJibriJid));
}
/**
* @return a string describing this session instance, used for logging
* purpose
*/
private String nickname()
{
return this.isSIP ? "SIP Jibri" : "Jibri";
}
/**
* Process a {@link JibriIq} *request* from Jibri
* @param request
* @return the response
*/
IQ processJibriIqRequestFromJibri(JibriIq request)
{
processJibriIqFromJibri(request);
return IQ.createResultIQ(request);
}
/**
* Process a {@link JibriIq} from Jibri (note that this
* may be an IQ request or an IQ response)
* @param iq
*/
private void processJibriIqFromJibri(JibriIq iq)
{
// We have something from Jibri - let's update recording status
JibriIq.Status status = iq.getStatus();
if (!JibriIq.Status.UNDEFINED.equals(status))
{
logger.info(
"Updating status from JIBRI: "
+ iq.toXML() + " for " + roomName);
handleJibriStatusUpdate(
iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry());
}
else
{
logger.error(
"Received UNDEFINED status from jibri: " + iq.toString());
}
}
/**
* Gets the recording mode of this jibri session
* @return the recording mode for this session (STREAM, FILE or UNDEFINED
* in the case that this isn't a recording session but actually a SIP
* session)
*/
JibriIq.RecordingMode getRecordingMode()
{
if (sipAddress != null)
{
return RecordingMode.UNDEFINED;
}
else if (streamID != null)
{
return RecordingMode.STREAM;
}
return RecordingMode.FILE;
}
/**
* Sends an IQ to the given Jibri instance and asks it to start
* recording/SIP call.
*/
private void sendJibriStartIq(final Jid jibriJid)
{
// Store Jibri JID to make the packet filter accept the response
currentJibriJid = jibriJid;
logger.info(
"Starting Jibri " + jibriJid
+ (isSIP
? ("for SIP address: " + sipAddress)
: (" for stream ID: " + streamID))
+ " in room: " + roomName);
final JibriIq startIq = new JibriIq();
startIq.setTo(jibriJid);
startIq.setType(IQ.Type.set);
startIq.setAction(JibriIq.Action.START);
startIq.setSessionId(this.sessionId);
logger.debug(
"Passing on jibri application data: " + this.applicationData);
startIq.setAppData(this.applicationData);
if (streamID != null)
{
startIq.setStreamId(streamID);
startIq.setRecordingMode(RecordingMode.STREAM);
if (youTubeBroadcastId != null) {
startIq.setYouTubeBroadcastId(youTubeBroadcastId);
}
}
else
{
startIq.setRecordingMode(RecordingMode.FILE);
}
startIq.setSipAddress(sipAddress);
startIq.setDisplayName(displayName);
// Insert name of the room into Jibri START IQ
startIq.setRoom(roomName);
// We will not wait forever for the Jibri to start. This method can be
// run multiple times on retry, so we want to restart the pending
// timeout each time.
reschedulePendingTimeout();
try
{
JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq);
processJibriIqFromJibri(result);
}
catch (OperationFailedException e)
{
logger.error("Error sending Jibri start IQ: " + e.toString());
}
}
/**
* Method schedules/reschedules {@link PendingStatusTimeout} which will
* clear recording state after
* {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}.
*/
private void reschedulePendingTimeout()
{
if (pendingTimeoutTask != null)
{
logger.info(
"Rescheduling pending timeout task for room: " + roomName);
pendingTimeoutTask.cancel(false);
}
if (pendingTimeout > 0)
{
pendingTimeoutTask
= scheduledExecutor.schedule(
new PendingStatusTimeout(),
pendingTimeout, TimeUnit.SECONDS);
}
}
/**
* Check whether or not we should retry the current request to another Jibri
* @return true if we've not exceeded the max amount of retries,
* false otherwise
*/
private boolean maxRetriesExceeded()
{
return (maxNumRetries >= 0 && numRetries >= maxNumRetries);
}
/**
* Retry the current request with another Jibri (if one is available)
* @return true if we were able to find another Jibri to retry the request
* with, false otherwise
*/
private boolean retryRequestWithAnotherJibri()
{
numRetries++;
return start();
}
/**
* Handle a Jibri status update (this could come from an IQ response, a new
* IQ from Jibri, an XMPP event, etc.).
* This will handle:
* 1) Retrying with a new Jibri in case of an error
* 2) Cleaning up the session when the Jibri session finished successfully
* (or there was an error but we have no more Jibris left to try)
* @param jibriJid the jid of the jibri for which this status update applies
* @param newStatus the jibri's new status
* @param failureReason the jibri's failure reason, if any (otherwise null)
* @param shouldRetryParam if {@code failureReason} is not null, shouldRetry
* denotes whether or not we should retry the same
* request with another Jibri
*/
private void handleJibriStatusUpdate(
@NotNull Jid jibriJid,
JibriIq.Status newStatus,
@Nullable JibriIq.FailureReason failureReason,
@Nullable Boolean shouldRetryParam)
{
jibriStatus = newStatus;
logger.info("Got Jibri status update: Jibri " + jibriJid
+ " has status " + newStatus
+ " and failure reason " + failureReason
+ ", current Jibri jid is " + currentJibriJid);
if (currentJibriJid == null)
{
logger.info("Current session has already been cleaned up, ignoring");
return;
}
if (jibriJid.compareTo(currentJibriJid) != 0)
{
logger.info("This status update is from " + jibriJid +
" but the current Jibri is " + currentJibriJid + ", ignoring");
return;
}
// First: if we're no longer pending (regardless of the Jibri's
// new state), make sure we stop the pending timeout task
if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus))
{
logger.info(
"Jibri is no longer pending, cancelling pending timeout task");
pendingTimeoutTask.cancel(false);
pendingTimeoutTask = null;
}
// Now, if there was a failure of any kind we'll try and find another
// Jibri to keep things going
if (failureReason != null)
{
boolean shouldRetry;
if (shouldRetryParam == null)
{
logger.warn("failureReason was non-null but shouldRetry " +
"wasn't set, will NOT retry");
shouldRetry = false;
}
else
{
shouldRetry = shouldRetryParam;
}
// There was an error with the current Jibri, see if we should retry
if (shouldRetry && !maxRetriesExceeded())
{
logger.info("Jibri failed, trying to fall back to another Jibri");
if (retryRequestWithAnotherJibri())
{
// The fallback to another Jibri succeeded.
logger.info("Successfully resumed session with another Jibri");
}
else
{
logger.info("Failed to fall back to another Jibri, this "
+ "session has now failed");
// Propagate up that the session has failed entirely.
// We'll pass the original failure reason.
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
}
else
{
if (!shouldRetry)
{
logger.info("Jibri failed and signaled that we " +
"should not retry the same request");
}
else
{
// The Jibri we tried failed and we've reached the maxmium
// amount of retries we've been configured to attempt, so we'll
// give up trying to handle this request.
logger.info("Jibri failed, but max amount of retries ("
+ maxNumRetries + ") reached, giving up");
}
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
}
else if (Status.OFF.equals(newStatus))
{
logger.info("Jibri session ended cleanly, notifying owner and "
+ "cleaning up session");
// The Jibri stopped for some non-error reason
owner.onSessionStateChanged(this, newStatus, failureReason);
cleanupSession();
}
else if (Status.ON.equals(newStatus))
{
logger.info("Jibri session started, notifying owner");
// The Jibri stopped for some non-error reason
owner.onSessionStateChanged(this, newStatus, failureReason);
}
}
/**
* @return SIP address received from Jitsi Meet, which is used for SIP
* gateway session (makes sense only for SIP sessions).
*/
String getSipAddress()
{
return sipAddress;
}
/**
* Get the unique ID for this session. This is used to uniquely
* identify a Jibri session instance, even of the same type (meaning,
* for example, that two file recordings would have different session
* IDs). It will be passed to Jibri and Jibri will put the session ID
* in its presence, so the Jibri user for a particular session can
* be identified by the clients.
* @return the session ID
*/
public String getSessionId()
{
return this.sessionId;
}
/**
* Helper class handles registration for the {@link JibriEvent}s.
*/
private class JibriEventHandler
extends EventHandlerActivator
{
private JibriEventHandler()
{
super(new String[]{
JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE});
}
@Override
public void handleEvent(Event event)
{
if (!JibriEvent.isJibriEvent(event))
{
logger.error("Invalid event: " + event);
return;
}
final JibriEvent jibriEvent = (JibriEvent) event;
final String topic = jibriEvent.getTopic();
final Jid jibriJid = jibriEvent.getJibriJid();
synchronized (JibriSession.this)
{
if (JibriEvent.WENT_OFFLINE.equals(topic)
&& jibriJid.equals(currentJibriJid))
{
logger.error(
nickname() + " went offline: " + jibriJid
+ " for room: " + roomName);
handleJibriStatusUpdate(
jibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* Task scheduled after we have received RESULT response from Jibri and
* entered PENDING state. Will abort the recording if we do not transit to
* ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}
* limit is exceeded.
*/
private class PendingStatusTimeout implements Runnable
{
public void run()
{
synchronized (JibriSession.this)
{
// Clear this task reference, so it won't be
// cancelling itself on status change from PENDING
pendingTimeoutTask = null;
if (isStartingStatus(jibriStatus))
{
logger.error(
nickname() + " pending timeout! " + roomName);
// If a Jibri times out during the pending phase, it's
// likely hung or having some issue. We'll send a stop (so
// if/when it does 'recover', it knows to stop) and simulate
// an error status (like we do in
// JibriEventHandler#handleEvent when a Jibri goes offline)
// to trigger the fallback logic.
stop(null);
handleJibriStatusUpdate(
currentJibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* The JID of the entity that has initiated the recording flow.
* @return The JID of the entity that has initiated the recording flow.
*/
public Jid getInitiator()
{
return initiator;
}
/**
* The JID of the entity that has initiated the stop of the recording.
* @return The JID of the entity that has stopped the recording.
*/
public Jid getTerminator()
{
return terminator;
}
/**
* Interface instance passed to {@link JibriSession} constructor which
* specifies the session owner which will be notified about any status
* changes.
*/
public interface Owner
{
/**
* Called on {@link JibriSession} status update.
* @param jibriSession which status has changed
* @param newStatus the new status
* @param failureReason optional error for {@link JibriIq.Status#OFF}.
*/
void onSessionStateChanged(
JibriSession jibriSession,
JibriIq.Status newStatus,
JibriIq.FailureReason failureReason);
}
}
|
73670_6 | package net.thevpc.scholar.hadruwaves.mom.str;
/**
* @author Taha Ben Salah ([email protected])
* @creationtime 17 sept. 2007 12:27:44
*/
public class ZinByGpFnConvergence {
// private MomStructure str;
// private GpTestFunctions[] gp;
// private FnBaseFunctions[] fn;
// private double[] widthOverLambda;
// private int[] indexes;
// private TreeSet<Integer> indexesOk=new TreeSet<Integer>();
// double delta;
// private int solutionGp;
// private int solutionFn;
// private double[] solutionZin;
// private Hashtable[] solutionZin;
//
// public ZinByGpFnConvergence(MomStructure str, FnBaseFunctions[] fn, GpTestFunctions[] gp, double[] widthOverLambda, int[] indexes,double delta) {
// this.str = str;
// this.fn = fn;
// this.gp = gp;
// this.widthOverLambda = widthOverLambda;
// this.indexes = indexes;
// this.delta = delta;
// }
//
// public compute(){
// while(true){
// }
}
| thevpc/scholar-mw | hadruwaves/hadruwaves-java/src/main/java/net/thevpc/scholar/hadruwaves/mom/str/ZinByGpFnConvergence.java | 331 | // private TreeSet<Integer> indexesOk=new TreeSet<Integer>(); | line_comment | nl | package net.thevpc.scholar.hadruwaves.mom.str;
/**
* @author Taha Ben Salah ([email protected])
* @creationtime 17 sept. 2007 12:27:44
*/
public class ZinByGpFnConvergence {
// private MomStructure str;
// private GpTestFunctions[] gp;
// private FnBaseFunctions[] fn;
// private double[] widthOverLambda;
// private int[] indexes;
// private TreeSet<Integer><SUF>
// double delta;
// private int solutionGp;
// private int solutionFn;
// private double[] solutionZin;
// private Hashtable[] solutionZin;
//
// public ZinByGpFnConvergence(MomStructure str, FnBaseFunctions[] fn, GpTestFunctions[] gp, double[] widthOverLambda, int[] indexes,double delta) {
// this.str = str;
// this.fn = fn;
// this.gp = gp;
// this.widthOverLambda = widthOverLambda;
// this.indexes = indexes;
// this.delta = delta;
// }
//
// public compute(){
// while(true){
// }
}
|
69088_0 | import domain.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testDAOHibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
public static void testDAOHibernate() {
AdresDAOHibernate adao = new AdresDAOHibernate(getSession());
ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession());
OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession());
ProductDAOHibernate pdao = new ProductDAOHibernate(getSession());
Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03"));
Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15);
OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15);
Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f);
System.out.println("------ REIZIGER -----");
System.out.println("--- save + findAll ---");
System.out.println(rdao.findAll());
rdao.save(reiziger);
System.out.println(rdao.findAll());
System.out.println("--- update + findById ---");
System.out.println(rdao.findById(reiziger.getId()));
System.out.println("\n\n------ ADRES -----");
System.out.println("--- save + findAll ---");
System.out.println(adao.findAll());
adao.save(adres);
System.out.println(adao.findAll());
System.out.println("--- update + findByReiziger ---");
adres.setHuisnummer("15a");
adao.update(adres);
System.out.println(adao.findByReiziger(reiziger));
System.out.println("--- delete ---");
adao.delete(adres);
System.out.println(adao.findAll());
System.out.println("\n\n------ PRODUCT -----");
System.out.println("--- save + findAll ---");
System.out.println(pdao.findAll());
pdao.save(product);
System.out.println(pdao.findAll());
System.out.println("--- update ---");
product.setPrijs(20.00f);
System.out.println(pdao.findAll());
System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----");
System.out.println("--- save ---");
odao.save(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
System.out.println("--- update ---");
ovChipkaart.setSaldo(2020.20f);
odao.update(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
// System.out.println("--- wijs product toe ---");
// ovChipkaart.getProductList().add(product);
// odao.update(ovChipkaart);
// System.out.println(odao.findByReiziger(reiziger));
System.out.println("\n\n----- DELETE ALLE -----");
System.out.println("--- delete ovchipkaart ---");
odao.delete(ovChipkaart);
System.out.println("--- delete product ---");
pdao.delete(product);
System.out.println(pdao.findAll());
System.out.println("---- delete reiziger ----");
rdao.delete(reiziger);
System.out.println(rdao.findById(reiziger.getId()));
}
}
| thijmon/hibernateDAO | src/main/java/Main.java | 1,592 | /**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/ | block_comment | nl | import domain.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze<SUF>*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testDAOHibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
public static void testDAOHibernate() {
AdresDAOHibernate adao = new AdresDAOHibernate(getSession());
ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession());
OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession());
ProductDAOHibernate pdao = new ProductDAOHibernate(getSession());
Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03"));
Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15);
OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15);
Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f);
System.out.println("------ REIZIGER -----");
System.out.println("--- save + findAll ---");
System.out.println(rdao.findAll());
rdao.save(reiziger);
System.out.println(rdao.findAll());
System.out.println("--- update + findById ---");
System.out.println(rdao.findById(reiziger.getId()));
System.out.println("\n\n------ ADRES -----");
System.out.println("--- save + findAll ---");
System.out.println(adao.findAll());
adao.save(adres);
System.out.println(adao.findAll());
System.out.println("--- update + findByReiziger ---");
adres.setHuisnummer("15a");
adao.update(adres);
System.out.println(adao.findByReiziger(reiziger));
System.out.println("--- delete ---");
adao.delete(adres);
System.out.println(adao.findAll());
System.out.println("\n\n------ PRODUCT -----");
System.out.println("--- save + findAll ---");
System.out.println(pdao.findAll());
pdao.save(product);
System.out.println(pdao.findAll());
System.out.println("--- update ---");
product.setPrijs(20.00f);
System.out.println(pdao.findAll());
System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----");
System.out.println("--- save ---");
odao.save(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
System.out.println("--- update ---");
ovChipkaart.setSaldo(2020.20f);
odao.update(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
// System.out.println("--- wijs product toe ---");
// ovChipkaart.getProductList().add(product);
// odao.update(ovChipkaart);
// System.out.println(odao.findByReiziger(reiziger));
System.out.println("\n\n----- DELETE ALLE -----");
System.out.println("--- delete ovchipkaart ---");
odao.delete(ovChipkaart);
System.out.println("--- delete product ---");
pdao.delete(product);
System.out.println(pdao.findAll());
System.out.println("---- delete reiziger ----");
rdao.delete(reiziger);
System.out.println(rdao.findById(reiziger.getId()));
}
}
|
85638_0 | package com.github.hanyaeger.tutorial.entities.zombies;
import com.github.hanyaeger.api.Coordinate2D;
import com.github.hanyaeger.api.entities.Collider;
import com.github.hanyaeger.tutorial.entities.plants.Plant;
public class BalloonZombie extends Zombie {
//zweeft over planten heen kan wel geraakt worden door pea
public BalloonZombie(Coordinate2D location) {
super(50, 1, location, "sprites/balloonZombie.gif", 2);
setMotion(0.5, 270d);
}
@Override
public void action() {
if(this.getHealth() <= 0){
remove();
}
}
@Override
public void onCollision(Collider collider) {
}
}
| thimovee/yaeger-game | src/main/java/com/github/hanyaeger/tutorial/entities/zombies/BalloonZombie.java | 230 | //zweeft over planten heen kan wel geraakt worden door pea | line_comment | nl | package com.github.hanyaeger.tutorial.entities.zombies;
import com.github.hanyaeger.api.Coordinate2D;
import com.github.hanyaeger.api.entities.Collider;
import com.github.hanyaeger.tutorial.entities.plants.Plant;
public class BalloonZombie extends Zombie {
//zweeft over<SUF>
public BalloonZombie(Coordinate2D location) {
super(50, 1, location, "sprites/balloonZombie.gif", 2);
setMotion(0.5, 270d);
}
@Override
public void action() {
if(this.getHealth() <= 0){
remove();
}
}
@Override
public void onCollision(Collider collider) {
}
}
|
129008_21 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
}
}
| thinkgem/jeesite | src/main/java/com/thinkgem/jeesite/common/utils/DateUtils.java | 2,060 | // long time = new Date().getTime()-parseDate("2012-11-19").getTime(); | line_comment | nl | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time<SUF>
// System.out.println(time/(24*60*60*1000));
}
}
|
54922_2 | package vb.week2.tabular;
/**
* VB prac week2: LaTeX tabular -> HTML symbolicName.
* Token class.
* @author Theo Ruys, Arend Rensink
* @version 2012.04.28
*/
public class Token {
public enum Kind {
IDENTIFIER("<IDENTIFIER>"),
NUM("<NUM>"),
BEGIN("begin"),
END("end"),
TABULAR("tabular"),
BSLASH("<BSLASH>"),
DOUBLE_BSLASH("<DOUBLE_BSLASH>"),
BAR("<BAR>"),
AMPERSAND("<AMPERSAND>"),
LCURLY("<LCURLY>"),
RCURLY("<RCURLY>"),
EOT("<EOT>");
private Kind(String spelling) {
this.spelling = spelling;
}
/** Returns the exact spelling of the keyword tokens. */
public String getSpelling() {
return this.spelling;
}
final private String spelling;
}
private Kind kind;
private String repr;
/**
* Construeert een Token-object gegeven de "kind" van het Token
* en zijn representatie. Als het een IDENTIFIER Token is wordt
* gecontroleerd of het geen "keyword" is.
* @param kind soort Token
* @param repr String representatie van het Token
*/
public Token(Kind kind, String repr) {
this.kind = kind;
this.repr = repr;
// Recognize keywords
if (this.kind == Kind.IDENTIFIER) {
for (Kind k: Kind.values()) {
if (repr.equals(k.getSpelling())) {
this.kind = k;
break;
}
}
}
}
/** Levert het soort Token. */
public Kind getKind() {
return this.kind;
}
/** Levert de String-representatie van dit Token. */
public String getRepr() {
return this.repr;
}
}
| thomasbrus/vertalerbouw | vb/week2/tabular/Token.java | 535 | /**
* Construeert een Token-object gegeven de "kind" van het Token
* en zijn representatie. Als het een IDENTIFIER Token is wordt
* gecontroleerd of het geen "keyword" is.
* @param kind soort Token
* @param repr String representatie van het Token
*/ | block_comment | nl | package vb.week2.tabular;
/**
* VB prac week2: LaTeX tabular -> HTML symbolicName.
* Token class.
* @author Theo Ruys, Arend Rensink
* @version 2012.04.28
*/
public class Token {
public enum Kind {
IDENTIFIER("<IDENTIFIER>"),
NUM("<NUM>"),
BEGIN("begin"),
END("end"),
TABULAR("tabular"),
BSLASH("<BSLASH>"),
DOUBLE_BSLASH("<DOUBLE_BSLASH>"),
BAR("<BAR>"),
AMPERSAND("<AMPERSAND>"),
LCURLY("<LCURLY>"),
RCURLY("<RCURLY>"),
EOT("<EOT>");
private Kind(String spelling) {
this.spelling = spelling;
}
/** Returns the exact spelling of the keyword tokens. */
public String getSpelling() {
return this.spelling;
}
final private String spelling;
}
private Kind kind;
private String repr;
/**
* Construeert een Token-object<SUF>*/
public Token(Kind kind, String repr) {
this.kind = kind;
this.repr = repr;
// Recognize keywords
if (this.kind == Kind.IDENTIFIER) {
for (Kind k: Kind.values()) {
if (repr.equals(k.getSpelling())) {
this.kind = k;
break;
}
}
}
}
/** Levert het soort Token. */
public Kind getKind() {
return this.kind;
}
/** Levert de String-representatie van dit Token. */
public String getRepr() {
return this.repr;
}
}
|
16621_3 | /*
* dex2jar - Tools to work with android .dex and java .class files
* Copyright (c) 2009-2013 Panxiaobo
*
* 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.googlecode.d2j.dex.writer.item;
import com.googlecode.d2j.dex.writer.ann.Off;
import com.googlecode.d2j.dex.writer.insn.Insn;
import com.googlecode.d2j.dex.writer.insn.Label;
import com.googlecode.d2j.dex.writer.insn.PreBuildInsn;
import com.googlecode.d2j.dex.writer.io.DataOut;
import com.googlecode.d2j.dex.writer.item.CodeItem.EncodedCatchHandler.AddrPair;
import com.googlecode.d2j.reader.Op;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
public class CodeItem extends BaseItem {
public int registersSize;
public int insSize;
public int outsSize;
public int insn_size;
public List<TryItem> tries;
@Off
public DebugInfoItem debugInfo;
public List<Insn> insns;
public List<EncodedCatchHandler> handlers;
@Override
public int place(int offset) {
offset += 16 + insn_size * 2;
if (tries != null && tries.size() > 0) {
if ((insn_size & 0x01) != 0) {// padding
offset += 2;
}
offset += 8 * tries.size();
if (handlers.size() > 0) {
int base = offset;
offset += lengthOfUleb128(handlers.size());
for (EncodedCatchHandler h : handlers) {
h.handler_off = offset - base;
int size = h.addPairs.size();
offset += lengthOfSleb128(h.catchAll != null ? -size : size);
for (AddrPair ap : h.addPairs) {
offset += lengthOfUleb128(ap.type.index) + lengthOfUleb128(ap.addr.offset);
}
if (h.catchAll != null) {
offset += lengthOfUleb128(h.catchAll.offset);
}
}
}
}
return offset;
}
@Override
public void write(DataOut out) {
out.ushort("registers_size", registersSize);
out.ushort("ins_size", insSize);
out.ushort("outs_size", outsSize);
out.ushort("tries_size", tries == null ? 0 : tries.size());
out.uint("debug_info_off", debugInfo == null ? 0 : debugInfo.offset);
out.uint("insn_size", insn_size);
ByteBuffer b = ByteBuffer.allocate(insn_size * 2).order(ByteOrder.LITTLE_ENDIAN);
for (Insn insn : insns) {
insn.write(b);
}
out.bytes("insn", b.array());
if (tries != null && tries.size() > 0) {
if ((insn_size & 0x01) != 0) {// padding
out.skip("padding", 2);
}
int lastEnd = 0;
for (TryItem ti : tries) {
if (ti.start.offset < lastEnd) {
System.err.println("'Out-of-order try' may throwed by libdex");
}
out.uint("start_addr", ti.start.offset);
out.ushort("insn_count", ti.end.offset - ti.start.offset);
lastEnd = ti.end.offset;
out.ushort("handler_off", ti.handler.handler_off);
}
if (handlers.size() > 0) {
out.uleb128("size", handlers.size());
for (EncodedCatchHandler h : handlers) {
int size = h.addPairs.size();
out.sleb128("size", (h.catchAll != null ? -size : size));
for (AddrPair ap : h.addPairs) {
out.uleb128("type_idx", (ap.type.index));
out.uleb128("addr", (ap.addr.offset));
}
if (h.catchAll != null) {
out.uleb128("catch_all_addr", (h.catchAll.offset));
}
}
}
}
}
public void prepareTries(List<TryItem> tryItems) {
if (tryItems.size() > 0) {
List<CodeItem.TryItem> uniqTrys = new ArrayList<>();
{ // merge dup trys
Set<TryItem> set = new HashSet<>();
for (CodeItem.TryItem tryItem : tryItems) {
if (!set.contains(tryItem)) {
uniqTrys.add(tryItem);
set.add(tryItem);
} else {
for (TryItem t : uniqTrys) {
if (t.equals(tryItem)) {
mergeExceptionHandler(t.handler, tryItem.handler);
}
}
}
}
set.clear();
this.tries = uniqTrys;
if (uniqTrys.size() > 0) {
Collections.sort(uniqTrys, new Comparator<TryItem>() {
@Override
public int compare(TryItem o1, TryItem o2) {
int x = o1.start.offset - o2.start.offset;
if (x == 0) {
x = o1.end.offset - o2.end.offset;
}
return x;
}
});
}
}
{ // merge dup handlers
List<CodeItem.EncodedCatchHandler> uniqHanders = new ArrayList<>();
Map<EncodedCatchHandler, EncodedCatchHandler> map = new HashMap<>();
for (CodeItem.TryItem tryItem : uniqTrys) {
CodeItem.EncodedCatchHandler d = tryItem.handler;
CodeItem.EncodedCatchHandler uH = map.get(d);
if (uH != null) {
tryItem.handler = uH;
} else {
uniqHanders.add(d);
map.put(d, d);
}
}
this.handlers = uniqHanders;
map.clear();
}
}
}
private void mergeExceptionHandler(EncodedCatchHandler to, EncodedCatchHandler from) {
for (AddrPair pair : from.addPairs) {
if (!to.addPairs.contains(pair)) {
to.addPairs.add(pair);
}
}
if (to.catchAll == null) {
to.catchAll = from.catchAll;
}
}
public void prepareInsns(List<Insn> ops, List<Insn> tailOps) {
int codeSize = 0;
for (Insn insn : ops) {
insn.offset = codeSize;
codeSize += insn.getCodeUnitSize();
}
for (Insn insn : tailOps) {
if ((codeSize & 1) != 0) { // not 32bit alignment
Insn nop = new PreBuildInsn(new byte[] { (byte) Op.NOP.opcode, 0 }); // f10x
insn.offset = codeSize;
codeSize += nop.getCodeUnitSize();
ops.add(nop);
}
insn.offset = codeSize;
codeSize += insn.getCodeUnitSize();
ops.add(insn);
}
tailOps.clear();
this.insns = ops;
this.insn_size = codeSize;
}
public static class EncodedCatchHandler {
public int handler_off;
public List<AddrPair> addPairs;
public Label catchAll;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
EncodedCatchHandler that = (EncodedCatchHandler) o;
if (!addPairs.equals(that.addPairs))
return false;
if (catchAll != null ? !catchAll.equals(that.catchAll) : that.catchAll != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = addPairs.hashCode();
result = 31 * result + (catchAll != null ? catchAll.offset : 0);
return result;
}
public static class AddrPair {
final public TypeIdItem type;
final public Label addr;
public AddrPair(TypeIdItem type, Label addr) {
this.type = type;
this.addr = addr;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AddrPair addrPair = (AddrPair) o;
if (addr.offset != addrPair.addr.offset)
return false;
if (!type.equals(addrPair.type))
return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + addr.offset;
return result;
}
}
}
public static class TryItem {
public Label start;
public Label end;
public EncodedCatchHandler handler;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
TryItem tryItem = (TryItem) o;
if (end.offset != tryItem.end.offset)
return false;
if (start.offset != tryItem.start.offset)
return false;
return true;
}
@Override
public int hashCode() {
int result = start.offset;
result = 31 * result + end.offset;
return result;
}
}
}
| thomasdarimont/dex2jar | dex-writer/src/main/java/com/googlecode/d2j/dex/writer/item/CodeItem.java | 2,905 | // not 32bit alignment | line_comment | nl | /*
* dex2jar - Tools to work with android .dex and java .class files
* Copyright (c) 2009-2013 Panxiaobo
*
* 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.googlecode.d2j.dex.writer.item;
import com.googlecode.d2j.dex.writer.ann.Off;
import com.googlecode.d2j.dex.writer.insn.Insn;
import com.googlecode.d2j.dex.writer.insn.Label;
import com.googlecode.d2j.dex.writer.insn.PreBuildInsn;
import com.googlecode.d2j.dex.writer.io.DataOut;
import com.googlecode.d2j.dex.writer.item.CodeItem.EncodedCatchHandler.AddrPair;
import com.googlecode.d2j.reader.Op;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
public class CodeItem extends BaseItem {
public int registersSize;
public int insSize;
public int outsSize;
public int insn_size;
public List<TryItem> tries;
@Off
public DebugInfoItem debugInfo;
public List<Insn> insns;
public List<EncodedCatchHandler> handlers;
@Override
public int place(int offset) {
offset += 16 + insn_size * 2;
if (tries != null && tries.size() > 0) {
if ((insn_size & 0x01) != 0) {// padding
offset += 2;
}
offset += 8 * tries.size();
if (handlers.size() > 0) {
int base = offset;
offset += lengthOfUleb128(handlers.size());
for (EncodedCatchHandler h : handlers) {
h.handler_off = offset - base;
int size = h.addPairs.size();
offset += lengthOfSleb128(h.catchAll != null ? -size : size);
for (AddrPair ap : h.addPairs) {
offset += lengthOfUleb128(ap.type.index) + lengthOfUleb128(ap.addr.offset);
}
if (h.catchAll != null) {
offset += lengthOfUleb128(h.catchAll.offset);
}
}
}
}
return offset;
}
@Override
public void write(DataOut out) {
out.ushort("registers_size", registersSize);
out.ushort("ins_size", insSize);
out.ushort("outs_size", outsSize);
out.ushort("tries_size", tries == null ? 0 : tries.size());
out.uint("debug_info_off", debugInfo == null ? 0 : debugInfo.offset);
out.uint("insn_size", insn_size);
ByteBuffer b = ByteBuffer.allocate(insn_size * 2).order(ByteOrder.LITTLE_ENDIAN);
for (Insn insn : insns) {
insn.write(b);
}
out.bytes("insn", b.array());
if (tries != null && tries.size() > 0) {
if ((insn_size & 0x01) != 0) {// padding
out.skip("padding", 2);
}
int lastEnd = 0;
for (TryItem ti : tries) {
if (ti.start.offset < lastEnd) {
System.err.println("'Out-of-order try' may throwed by libdex");
}
out.uint("start_addr", ti.start.offset);
out.ushort("insn_count", ti.end.offset - ti.start.offset);
lastEnd = ti.end.offset;
out.ushort("handler_off", ti.handler.handler_off);
}
if (handlers.size() > 0) {
out.uleb128("size", handlers.size());
for (EncodedCatchHandler h : handlers) {
int size = h.addPairs.size();
out.sleb128("size", (h.catchAll != null ? -size : size));
for (AddrPair ap : h.addPairs) {
out.uleb128("type_idx", (ap.type.index));
out.uleb128("addr", (ap.addr.offset));
}
if (h.catchAll != null) {
out.uleb128("catch_all_addr", (h.catchAll.offset));
}
}
}
}
}
public void prepareTries(List<TryItem> tryItems) {
if (tryItems.size() > 0) {
List<CodeItem.TryItem> uniqTrys = new ArrayList<>();
{ // merge dup trys
Set<TryItem> set = new HashSet<>();
for (CodeItem.TryItem tryItem : tryItems) {
if (!set.contains(tryItem)) {
uniqTrys.add(tryItem);
set.add(tryItem);
} else {
for (TryItem t : uniqTrys) {
if (t.equals(tryItem)) {
mergeExceptionHandler(t.handler, tryItem.handler);
}
}
}
}
set.clear();
this.tries = uniqTrys;
if (uniqTrys.size() > 0) {
Collections.sort(uniqTrys, new Comparator<TryItem>() {
@Override
public int compare(TryItem o1, TryItem o2) {
int x = o1.start.offset - o2.start.offset;
if (x == 0) {
x = o1.end.offset - o2.end.offset;
}
return x;
}
});
}
}
{ // merge dup handlers
List<CodeItem.EncodedCatchHandler> uniqHanders = new ArrayList<>();
Map<EncodedCatchHandler, EncodedCatchHandler> map = new HashMap<>();
for (CodeItem.TryItem tryItem : uniqTrys) {
CodeItem.EncodedCatchHandler d = tryItem.handler;
CodeItem.EncodedCatchHandler uH = map.get(d);
if (uH != null) {
tryItem.handler = uH;
} else {
uniqHanders.add(d);
map.put(d, d);
}
}
this.handlers = uniqHanders;
map.clear();
}
}
}
private void mergeExceptionHandler(EncodedCatchHandler to, EncodedCatchHandler from) {
for (AddrPair pair : from.addPairs) {
if (!to.addPairs.contains(pair)) {
to.addPairs.add(pair);
}
}
if (to.catchAll == null) {
to.catchAll = from.catchAll;
}
}
public void prepareInsns(List<Insn> ops, List<Insn> tailOps) {
int codeSize = 0;
for (Insn insn : ops) {
insn.offset = codeSize;
codeSize += insn.getCodeUnitSize();
}
for (Insn insn : tailOps) {
if ((codeSize & 1) != 0) { // not 32bit<SUF>
Insn nop = new PreBuildInsn(new byte[] { (byte) Op.NOP.opcode, 0 }); // f10x
insn.offset = codeSize;
codeSize += nop.getCodeUnitSize();
ops.add(nop);
}
insn.offset = codeSize;
codeSize += insn.getCodeUnitSize();
ops.add(insn);
}
tailOps.clear();
this.insns = ops;
this.insn_size = codeSize;
}
public static class EncodedCatchHandler {
public int handler_off;
public List<AddrPair> addPairs;
public Label catchAll;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
EncodedCatchHandler that = (EncodedCatchHandler) o;
if (!addPairs.equals(that.addPairs))
return false;
if (catchAll != null ? !catchAll.equals(that.catchAll) : that.catchAll != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = addPairs.hashCode();
result = 31 * result + (catchAll != null ? catchAll.offset : 0);
return result;
}
public static class AddrPair {
final public TypeIdItem type;
final public Label addr;
public AddrPair(TypeIdItem type, Label addr) {
this.type = type;
this.addr = addr;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AddrPair addrPair = (AddrPair) o;
if (addr.offset != addrPair.addr.offset)
return false;
if (!type.equals(addrPair.type))
return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + addr.offset;
return result;
}
}
}
public static class TryItem {
public Label start;
public Label end;
public EncodedCatchHandler handler;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
TryItem tryItem = (TryItem) o;
if (end.offset != tryItem.end.offset)
return false;
if (start.offset != tryItem.start.offset)
return false;
return true;
}
@Override
public int hashCode() {
int result = start.offset;
result = 31 * result + end.offset;
return result;
}
}
}
|
165678_4 | package nl.topicus.djodd.stats;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class Common {
public static final ImmutableList<String> discardStates = ImmutableList.of("resolved", "closed", "afgemeld", "afgesloten");
public static final ImmutableList<String> resolvedStates = ImmutableList.of("resolved", "afgemeld");
public static final ImmutableList<String> closedStates = ImmutableList.of("closed", "afgesloten");
public static HtmlPage switchToProject(String project, HtmlPage currentPage) throws IOException
{
HtmlForm form = currentPage.getFormByName("form_set_project");
HtmlSubmitInput submit;
try
{
submit = form.getInputByValue("Switch");
}
catch(ElementNotFoundException e)
{
submit = form.getInputByValue("Wisselen");
}
HtmlSelect select = form.getSelectByName("project_id");
select.setSelectedAttribute("210", true);
return submit.click();
}
public static HtmlPage login(WebClient webClient, String host, String username, String password) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
System.out.println("Attempting to login...");
final HtmlPage page = webClient.getPage(host);
final HtmlForm form = page.getFormByName("login_form");
final HtmlSubmitInput button = form.getInputByValue("Login");
final HtmlTextInput Iusername = form.getInputByName("username");
final HtmlPasswordInput Ipassword = form.getInputByName("password");
// Change the value of the text field
Iusername.setValueAttribute(username);
Ipassword.setValueAttribute(password);
// Now submit the form by clicking the button and get back the second page.
return button.click();
}
public static List<HtmlOption> getVersions(WebClient webClient, String host) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
HtmlPage info_page = webClient.getPage(host + "/view_filters_page.php?for_screen=1&target_field=target_version[]");
HtmlForm filters = info_page.getFormByName("filters");
HtmlSelect target_version = filters.getSelectByName("target_version[]");
List<HtmlOption> versions = target_version.getOptions();
return versions;
}
protected static void extractIssueStates(final WebClient webClient, String host, List<Integer> issues,
Map<Integer, TreeMap<DateTime, String>> issue_version,
Map<Integer, TreeMap<DateTime, String>> issue_status,
Map<Integer, TreeMap<DateTime, String>> issue_assigned_to)
throws IOException, MalformedURLException {
int index = 1;
for(Integer issue : issues)
{
HtmlPage page = getIssueHistoryPage(issue, webClient, host);
issue_version.put(issue, getIssueHistory(issue, page, "Target Version"));
issue_status.put(issue, getIssueHistory(issue, page, "Status"));
issue_assigned_to.put(issue, getIssueHistory(issue, page, "Assigned To"));
index++;
System.out.println(String.format("Progress %f", ((float) index / issues.size()) * 100));
}
}
public static HtmlPage getIssueHistoryPage(int id, WebClient web, String host) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
System.out.println("Getting issues history for: " + id);
HtmlPage page = web.getPage(host+"/view.php?id="+id);
return page;
}
public static TreeMap<DateTime, String> getIssueHistory(int id, HtmlPage page, String desiredType) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
TreeMap<DateTime, String> result = new TreeMap<DateTime, String>();
//parse 'date submitted' en 'target version', 'Status' fields
final DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DomElement info_table = page.getElementsByTagName("table").get(2);
DateTime date = fmt.parseDateTime(info_table.getElementsByTagName("tr").get(2).getElementsByTagName("td").get(4).asText()); //first submitted
//String status = info_table.getElementsByTagName("tr").get(7).getElementsByTagName("td").get(1).asText();
String version = info_table.getElementsByTagName("tr").get(10).getElementsByTagName("td").get(1).asText().replaceAll("\\[.*\\] ", "");
String assigned_to = info_table.getElementsByTagName("tr").get(5).getElementsByTagName("td").get(1).asText().trim();
if (desiredType.equals("Status"))
{
result.put(date, "New");
}
else if (desiredType.equals("Target Version"))
{
result.put(date, version);
}
else if (desiredType.equals("Assigned To"))
{
result.put(date, assigned_to);
}
//loop de history tabel door
DomElement history = page.getElementById("history_open");
if (history != null)
{
for(HtmlElement row : history.getElementsByTagName("tr"))
{
ArrayList<DomElement> columns = Lists.newArrayList(row.getChildElements());
if (columns.size() == 4 &&
!columns.get(0).getTextContent().contains("Date Modified") &&
!columns.get(0).getTextContent().contains("Gewijzigd op")
)
{
final DateTime timestamp = fmt.parseDateTime(columns.get(0).getTextContent().trim());
//final String user = columns.get(1).getTextContent().trim();
final String type = columns.get(2).getTextContent().trim();
final String value = columns.get(3).getTextContent().trim().replaceAll(".*=\\>", "").trim();
if (type.equals((desiredType)))
{
//System.out.println(timestamp + " : " + type + " = " + value);
result.put(timestamp, value);
}
}
}
}
else
{
System.out.println(String.format("History info div not available in page for issue %s", id));
}
return result;
}
/**
* Get the release versions, WARNING: only works with certain Mantis accounts
* @param webClient
* @return
* @throws IOException
* @throws MalformedURLException
* @throws FailingHttpStatusCodeException
*/
public static Map<String, LocalDate> getReleaseDates(WebClient webClient, String host, String project_id) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
Map<String, LocalDate> result = new HashMap<String, LocalDate>();
HtmlPage page = webClient.getPage(host+"/manage_proj_edit_page.php?project_id="+project_id);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
HtmlAnchor a = page.getAnchorByName("versions");
List<HtmlElement> rows = a.getHtmlElementsByTagName("tr");
for(HtmlElement row : rows)
{
List<HtmlElement> cells = row.getHtmlElementsByTagName("td");
if (cells.size() == 5 && !cells.get(0).asText().equals("Versie") && !cells.get(0).asText().equals("Version"))
{
String version = cells.get(0).asText();
LocalDate date = formatter.parseLocalDate(cells.get(3).asText().substring(0, 10));
result.put(version, date);
}
}
return result;
}
public static List<Integer> getIssues(WebClient webClient, String host, String desiredVersion) throws IOException
{
System.out.println("Getting issues for version : " + desiredVersion);
HtmlPage info_page = webClient.getPage(host+"/view_filters_page.php?for_screen=1&target_field=target_version[]");
HtmlForm filters = info_page.getFormByName("filters");
HtmlSelect target_version = filters.getSelectByName("target_version[]");
List<HtmlOption> versions = target_version.getOptions();
HtmlOption version = null;
for(HtmlOption curVersion : versions)
{
if (curVersion.asText().equals(desiredVersion)) version = curVersion;
}
HtmlSubmitInput submit = filters.getInputByName("filter");
target_version.setSelectedAttribute(version, true);
HtmlInput per_page = filters.getInputByName("per_page");
per_page.setValueAttribute("5000");
filters.getSelectByName("custom_field_78[]").setSelectedAttribute("0", true); //knownbug
filters.getSelectByName("custom_field_40[]").setSelectedAttribute("0", true); //school
filters.getSelectByName("custom_field_47[]").setSelectedAttribute("0", true); //SOM omgeving
filters.getSelectByName("custom_field_118[]").setSelectedAttribute("0", true); //Doelgroep
filters.getSelectByName("hide_status[]").setSelectedAttribute("-2", true);
HtmlPage issuesPage = submit.click();
List<Integer> issues = new ArrayList<Integer>();
for(HtmlElement sub : issuesPage.getElementById("buglist").getHtmlElementDescendants())
{
if (sub.getTagName().equals("a"))
{
if (sub.getAttribute("href").startsWith("/view.php?id="))
{
issues.add(Integer.parseInt(sub.getTextContent()));
}
}
}
System.out.println(String.format("Number of issues found: %d", issues.size()));
return issues;
}
public static WebClient getWebClient()
{
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setJavaScriptEnabled(false);
return webClient;
}
public static List<HtmlOption> getVersionsReleasedAfter(Map<String, LocalDate> releaseDates, List<HtmlOption> recent, LocalDate date)
{
List<HtmlOption> filtered_recent = new ArrayList<HtmlOption>();
for( Entry<String, LocalDate> version_info : releaseDates.entrySet())
{
if (version_info.getValue().plusDays(1).isAfter(date)) //fix voor isAfterOrEqual
{
String version = version_info.getKey();
for(HtmlOption option : recent)
{
if (option.asText().equals(version))
{
filtered_recent.add(option);
}
}
}
}
return filtered_recent;
}
}
| thomasmarkus/mantis-stats | src/main/java/nl/topicus/djodd/stats/Common.java | 3,352 | //loop de history tabel door | line_comment | nl | package nl.topicus.djodd.stats;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class Common {
public static final ImmutableList<String> discardStates = ImmutableList.of("resolved", "closed", "afgemeld", "afgesloten");
public static final ImmutableList<String> resolvedStates = ImmutableList.of("resolved", "afgemeld");
public static final ImmutableList<String> closedStates = ImmutableList.of("closed", "afgesloten");
public static HtmlPage switchToProject(String project, HtmlPage currentPage) throws IOException
{
HtmlForm form = currentPage.getFormByName("form_set_project");
HtmlSubmitInput submit;
try
{
submit = form.getInputByValue("Switch");
}
catch(ElementNotFoundException e)
{
submit = form.getInputByValue("Wisselen");
}
HtmlSelect select = form.getSelectByName("project_id");
select.setSelectedAttribute("210", true);
return submit.click();
}
public static HtmlPage login(WebClient webClient, String host, String username, String password) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
System.out.println("Attempting to login...");
final HtmlPage page = webClient.getPage(host);
final HtmlForm form = page.getFormByName("login_form");
final HtmlSubmitInput button = form.getInputByValue("Login");
final HtmlTextInput Iusername = form.getInputByName("username");
final HtmlPasswordInput Ipassword = form.getInputByName("password");
// Change the value of the text field
Iusername.setValueAttribute(username);
Ipassword.setValueAttribute(password);
// Now submit the form by clicking the button and get back the second page.
return button.click();
}
public static List<HtmlOption> getVersions(WebClient webClient, String host) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
HtmlPage info_page = webClient.getPage(host + "/view_filters_page.php?for_screen=1&target_field=target_version[]");
HtmlForm filters = info_page.getFormByName("filters");
HtmlSelect target_version = filters.getSelectByName("target_version[]");
List<HtmlOption> versions = target_version.getOptions();
return versions;
}
protected static void extractIssueStates(final WebClient webClient, String host, List<Integer> issues,
Map<Integer, TreeMap<DateTime, String>> issue_version,
Map<Integer, TreeMap<DateTime, String>> issue_status,
Map<Integer, TreeMap<DateTime, String>> issue_assigned_to)
throws IOException, MalformedURLException {
int index = 1;
for(Integer issue : issues)
{
HtmlPage page = getIssueHistoryPage(issue, webClient, host);
issue_version.put(issue, getIssueHistory(issue, page, "Target Version"));
issue_status.put(issue, getIssueHistory(issue, page, "Status"));
issue_assigned_to.put(issue, getIssueHistory(issue, page, "Assigned To"));
index++;
System.out.println(String.format("Progress %f", ((float) index / issues.size()) * 100));
}
}
public static HtmlPage getIssueHistoryPage(int id, WebClient web, String host) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
System.out.println("Getting issues history for: " + id);
HtmlPage page = web.getPage(host+"/view.php?id="+id);
return page;
}
public static TreeMap<DateTime, String> getIssueHistory(int id, HtmlPage page, String desiredType) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
TreeMap<DateTime, String> result = new TreeMap<DateTime, String>();
//parse 'date submitted' en 'target version', 'Status' fields
final DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DomElement info_table = page.getElementsByTagName("table").get(2);
DateTime date = fmt.parseDateTime(info_table.getElementsByTagName("tr").get(2).getElementsByTagName("td").get(4).asText()); //first submitted
//String status = info_table.getElementsByTagName("tr").get(7).getElementsByTagName("td").get(1).asText();
String version = info_table.getElementsByTagName("tr").get(10).getElementsByTagName("td").get(1).asText().replaceAll("\\[.*\\] ", "");
String assigned_to = info_table.getElementsByTagName("tr").get(5).getElementsByTagName("td").get(1).asText().trim();
if (desiredType.equals("Status"))
{
result.put(date, "New");
}
else if (desiredType.equals("Target Version"))
{
result.put(date, version);
}
else if (desiredType.equals("Assigned To"))
{
result.put(date, assigned_to);
}
//loop de<SUF>
DomElement history = page.getElementById("history_open");
if (history != null)
{
for(HtmlElement row : history.getElementsByTagName("tr"))
{
ArrayList<DomElement> columns = Lists.newArrayList(row.getChildElements());
if (columns.size() == 4 &&
!columns.get(0).getTextContent().contains("Date Modified") &&
!columns.get(0).getTextContent().contains("Gewijzigd op")
)
{
final DateTime timestamp = fmt.parseDateTime(columns.get(0).getTextContent().trim());
//final String user = columns.get(1).getTextContent().trim();
final String type = columns.get(2).getTextContent().trim();
final String value = columns.get(3).getTextContent().trim().replaceAll(".*=\\>", "").trim();
if (type.equals((desiredType)))
{
//System.out.println(timestamp + " : " + type + " = " + value);
result.put(timestamp, value);
}
}
}
}
else
{
System.out.println(String.format("History info div not available in page for issue %s", id));
}
return result;
}
/**
* Get the release versions, WARNING: only works with certain Mantis accounts
* @param webClient
* @return
* @throws IOException
* @throws MalformedURLException
* @throws FailingHttpStatusCodeException
*/
public static Map<String, LocalDate> getReleaseDates(WebClient webClient, String host, String project_id) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
Map<String, LocalDate> result = new HashMap<String, LocalDate>();
HtmlPage page = webClient.getPage(host+"/manage_proj_edit_page.php?project_id="+project_id);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
HtmlAnchor a = page.getAnchorByName("versions");
List<HtmlElement> rows = a.getHtmlElementsByTagName("tr");
for(HtmlElement row : rows)
{
List<HtmlElement> cells = row.getHtmlElementsByTagName("td");
if (cells.size() == 5 && !cells.get(0).asText().equals("Versie") && !cells.get(0).asText().equals("Version"))
{
String version = cells.get(0).asText();
LocalDate date = formatter.parseLocalDate(cells.get(3).asText().substring(0, 10));
result.put(version, date);
}
}
return result;
}
public static List<Integer> getIssues(WebClient webClient, String host, String desiredVersion) throws IOException
{
System.out.println("Getting issues for version : " + desiredVersion);
HtmlPage info_page = webClient.getPage(host+"/view_filters_page.php?for_screen=1&target_field=target_version[]");
HtmlForm filters = info_page.getFormByName("filters");
HtmlSelect target_version = filters.getSelectByName("target_version[]");
List<HtmlOption> versions = target_version.getOptions();
HtmlOption version = null;
for(HtmlOption curVersion : versions)
{
if (curVersion.asText().equals(desiredVersion)) version = curVersion;
}
HtmlSubmitInput submit = filters.getInputByName("filter");
target_version.setSelectedAttribute(version, true);
HtmlInput per_page = filters.getInputByName("per_page");
per_page.setValueAttribute("5000");
filters.getSelectByName("custom_field_78[]").setSelectedAttribute("0", true); //knownbug
filters.getSelectByName("custom_field_40[]").setSelectedAttribute("0", true); //school
filters.getSelectByName("custom_field_47[]").setSelectedAttribute("0", true); //SOM omgeving
filters.getSelectByName("custom_field_118[]").setSelectedAttribute("0", true); //Doelgroep
filters.getSelectByName("hide_status[]").setSelectedAttribute("-2", true);
HtmlPage issuesPage = submit.click();
List<Integer> issues = new ArrayList<Integer>();
for(HtmlElement sub : issuesPage.getElementById("buglist").getHtmlElementDescendants())
{
if (sub.getTagName().equals("a"))
{
if (sub.getAttribute("href").startsWith("/view.php?id="))
{
issues.add(Integer.parseInt(sub.getTextContent()));
}
}
}
System.out.println(String.format("Number of issues found: %d", issues.size()));
return issues;
}
public static WebClient getWebClient()
{
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setJavaScriptEnabled(false);
return webClient;
}
public static List<HtmlOption> getVersionsReleasedAfter(Map<String, LocalDate> releaseDates, List<HtmlOption> recent, LocalDate date)
{
List<HtmlOption> filtered_recent = new ArrayList<HtmlOption>();
for( Entry<String, LocalDate> version_info : releaseDates.entrySet())
{
if (version_info.getValue().plusDays(1).isAfter(date)) //fix voor isAfterOrEqual
{
String version = version_info.getKey();
for(HtmlOption option : recent)
{
if (option.asText().equals(version))
{
filtered_recent.add(option);
}
}
}
}
return filtered_recent;
}
}
|
192328_41 | package de.yard.threed.engine.loader;
import de.yard.threed.core.Color;
import de.yard.threed.core.ColorType;
import de.yard.threed.core.NumericType;
import de.yard.threed.core.NumericValue;
import de.yard.threed.core.StringUtils;
import de.yard.threed.core.loader.PortableMaterial;
import de.yard.threed.core.loader.PortableModelDefinition;
import de.yard.threed.core.loader.PortableModelList;
import de.yard.threed.core.platform.Config;
import de.yard.threed.core.platform.Log;
import de.yard.threed.core.platform.NativeCamera;
import de.yard.threed.core.platform.NativeGeometry;
import de.yard.threed.core.platform.NativeMaterial;
import de.yard.threed.core.platform.NativeTexture;
import de.yard.threed.core.platform.Platform;
import de.yard.threed.core.resource.Bundle;
import de.yard.threed.core.resource.BundleRegistry;
import de.yard.threed.core.resource.BundleResource;
import de.yard.threed.core.resource.NativeResource;
import de.yard.threed.core.resource.ResourceLoader;
import de.yard.threed.core.resource.ResourcePath;
import de.yard.threed.core.geometry.SimpleGeometry;
import de.yard.threed.core.resource.URL;
import de.yard.threed.engine.GenericGeometry;
import de.yard.threed.engine.Material;
import de.yard.threed.engine.Mesh;
import de.yard.threed.engine.PerspectiveCamera;
import de.yard.threed.engine.SceneNode;
import de.yard.threed.engine.Texture;
import de.yard.threed.engine.platform.EngineHelper;
import de.yard.threed.engine.platform.ResourceLoaderFromBundle;
import de.yard.threed.engine.platform.common.AbstractSceneRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 06.12.22: A builder for universal model specification.
*/
public class PortableModelBuilder {
static Log logger = Platform.getInstance().getLog(PortableModelBuilder.class);
// Material, das verwendet wird, wenn das eigentlich definierte nicht bekannt ist
private NativeMaterial dummyMaterial;
//ResourcePath defaulttexturebasepath;
PortableModelList pml;
//Just an indicator for testing
public boolean dummymaterialused;
public PortableModelBuilder(PortableModelList pml) {
this.pml = pml;
}
/*public PortableModelBuilder(ResourcePath texturebasepath, List<GeoMat> gml) {
this.defaulttexturebasepath = texturebasepath;
this.gml = gml;
/*TODO erstmal material in gltf klaeren for (GeoMat gm : gml){
PreprocessedLoadedObject ppo = new PreprocessedLoadedObject();
ppo.geolist=new ArrayList<SimpleGeometry>();
ppo.geolist.add(gm.geo);
objects.add(ppo);
LoadedMaterial ppm = new LoadedMaterial();
ppm.
materials.add(ppm);
}* /
}*/
/**
* ResourceLoader is needed in builder for loading textures.
* <p>
* alttexturepath might be null. Then texturebasepath is used.
*
* @return
*/
public SceneNode buildModel(ResourceLoader resourceLoader) {
return buildModel(resourceLoader, null);
}
public SceneNode buildModel(ResourceLoader resourceLoader, ResourcePath alttexturepath) {
SceneNode rootnode = new SceneNode();
if (pml.getName() != null) {
rootnode.setName(pml.getName());
}
for (int i = 0; i < pml.getObjectCount(); i++) {
SceneNode newModel = buildModel(resourceLoader, pml.getObject(i), alttexturepath);
String parent = pml.getParent(i);
SceneNode destinationNode = rootnode;
if (parent != null) {
logger.debug("looking for parent " + parent);
NativeCamera camera = AbstractSceneRunner.getInstance().findCameraByName(parent);
PerspectiveCamera perspectiveCamera = new PerspectiveCamera(camera);
destinationNode = perspectiveCamera.getCarrier();
// attach to carrier will propagate layer. newModel.getTransform().setLayer(perspectiveCamera.getLayer());
logger.debug("found parent camera with layer " + perspectiveCamera.getLayer());
}
destinationNode.attach(newModel);
}
return rootnode;
}
private SceneNode buildModel(ResourceLoader resourceLoader, PortableModelDefinition obj, ResourcePath alttexturepath/*, boolean dummywegensignatureindeutigkeit*/) {
//this.bundle = bundle;
//this.rpath = rpath;
ResourcePath nr = pml.defaulttexturebasepath;
if (alttexturepath != null) {
nr = alttexturepath;
}
return buildObject(resourceLoader, obj /*, null/*, matlist*/, nr);
}
private SceneNode buildObject(ResourceLoader resourceLoader, PortableModelDefinition obj, /*MaterialPool matpool,*/ ResourcePath texturebasepath) {
/*30.12.17 Es kann mit GLTF auch leere Objekte geben if (obj.geolist == null) {
throw new RuntimeException("geo not preprocessed");
}*/
// Eine Liste der Materialien DIESES Objects anlegen.
// Nur die in den Facelisten des Objekts wirklich verwendeten Materialien anlegen. Sonst stimmt
// die Zuordnung nicht. 2.5.19: Spaetestens seit Flat Shading ist es noch nicht sicher, wie das Material konkret angelegt werden muss. Darum
// die Matlist nur mit MaterialDefinitionen anlegen.
// 2.5.19: matpool: aknn man sicher sein, dass es wirklich dasselbe ist? Z.B (un/flat)shaded. Eigentlich ist es doch ein zugrosses Risiko im Vergleich zum Nutzen, oder?
// mal weglassen
/*30.12.17: das pruef ich auch nicht mehr
if (obj.geolistmaterial.size() == 0) {
// Kommt wolh bei RollerCoaster.ac schon mal vor.
logger.warn("facelistmaterial isType empty in " + obj.name);
}*/
List<PortableMaterial/*NativeMaterial*/> matlist = buildMatlist(/*13.2.24 bundle,*/ obj, /*matpool,*/ texturebasepath);
boolean wireframe = false;
if (wireframe) {
for (int i = 0; i < matlist.size(); i++) {
matlist.set(i, null);
}
}
SceneNode model = new SceneNode();
String name;
if (StringUtils.empty(obj.name)) {
name = "<no name>";
} else {
name = obj.name;
}
model.setName(name);
if (obj.translation != null) {
model.getTransform().setPosition((obj.translation));
}
if (obj.rotation != null) {
model.getTransform().setRotation((obj.rotation));
}
// Keine leeren Objekte anlegen (z.B. AC World). Als Node aber schon. Die AC kids Hierarchie soll erhalten bleiben.
if (obj.geolist != null && obj.geolist.size() > 0) {
if (obj.geolist.size() > 1/*faces.size() > 1 && matlist.size() > 1*/) {
//List<SimpleGeometry> geolist = GeometryHelper.prepareGeometry(obj.vertices, obj.faces, /*matlist,*/ null, true, obj.crease);
//2.5.19: Gibt es das seit GLTF ueberhauot noch? Ja, eine Node kann doch mehrere Meshes haben, oder?
SceneNode m = buildSceneNode(resourceLoader, obj.geolist, matlist, false, false, texturebasepath/*3.5.19, obj.texture*/);
m.setName(obj.name);
model.attach(m);
} else {
//List<SimpleGeometry> geolist = GeometryHelper.prepareGeometry(obj.vertices, obj.faces, /*matlist,*/ null, false, obj.crease);
//if (geolist.size() > 1) {
// throw new RuntimeException("unexpected multiple geos");
//}
if (obj.geolist.size() == 0) {
logger.error("no geo list");
}
PortableMaterial/*NativeMaterial*/ mate = null;
if (matlist.size() == 0) {
logger.error("no matlist in " + obj.name);
} else {
mate = matlist.get(0);
}
//2.5.19: Neu an dieser Stelle
NativeMaterial nmat = buildMaterialFromPortableMaterial(resourceLoader, mate, texturebasepath, /*3.5.19obj.texture, */obj.geolist.get(0).getNormals() != null);
Mesh mesh = new Mesh(new GenericGeometry(obj.geolist.get(0)).getNativeGeometry(), nmat/*mate*/, false, false);
model.setMesh(mesh);
}
}
for (int i = 0; i < obj.kids.size(); i++) {
model.attach(buildObject(resourceLoader, obj.kids.get(i)/*, matpool/*, matlist*/, texturebasepath));
}
if (Config.modelloaddebuglog) {
logger.debug("buildObject complete " + name);
}
return model;
}
NativeMaterial buildMaterialFromPortableMaterial(ResourceLoader resourceLoader, /*Bundle bundle,*/ PortableMaterial portableMaterial, ResourcePath texturebasepath/*3.5.19, String objtexture*/, boolean hasnormals) {
NativeMaterial nmat;
if (portableMaterial != null) {
//Auf AC zugeschnitten, denn nur die(?) haben die Textur am Object.
//22.12.17: Darum jetzt bevorzugt den Texturename aus dem Material.
Material ma = /*PortableMaterial.*/buildMaterial(/*bundle*/resourceLoader, portableMaterial, /*3.5.19(portableMaterial.texture != null) ? * 14.2.24 /portableMaterial.texture/*3.5.19 : objtexture*/ texturebasepath, hasnormals);
if (ma == null) {
logger.warn("No material. Using dummy material.");
nmat = getDummyMaterial();
} else {
nmat = ma.material;
}
} else {
nmat = getDummyMaterial();
}
return nmat;
}
/**
* Teil einer fruehere Platform.buildMeshG() Methode.
* 10.3.16: Da auch WebGl und Opengl keine multiple material koennen, den extract aus JME hierauf gezogen. Auch weil es erstmal ganz gut funktioniert.
* 02.05.16: Im Sinne der Vereinfachung generell keine multiple material vorsehen, auch wenn Unity es kann. Die Engine extrahiert jetzt Submeshes.
* Ist in Model statt in Mesh, weil durch die Aufsplittung ja auch ein Model rauskommt. Die Methode ist jetzt auch wirklich nur fuer Multi Material gedacht.
* 2.5.19: War mal Constructor von SceneNode. Passt da aber nicht hin.
*/
public SceneNode buildSceneNode(ResourceLoader resourceLoader, /*Bundle bundle,*/ List<SimpleGeometry> geolist, List<PortableMaterial> material, boolean castShadow, boolean receiveShadow, ResourcePath texturebasepath/*3.5.19, String objtexture*/) {
//this();
SceneNode mainsn = new SceneNode();
int i = 0;
for (SimpleGeometry geo : geolist) {
NativeGeometry ng = EngineHelper.buildGeometry(geo.getVertices(), /*new SmartArrayList<Face3List>(*/geo.getIndices(), geo.getUvs(), geo.getNormals());
//2.5.19: Neu an dieser Stelle
NativeMaterial nmat = buildMaterialFromPortableMaterial(resourceLoader, material.get(i), texturebasepath, /*3.5.19objtexture,*/ geo.getNormals() != null);
Mesh submesh = new Mesh(ng, nmat/*material.get(i)*/, castShadow, receiveShadow);
// add(new SceneNode(submesh));
SceneNode sn = new SceneNode(submesh);
sn.nativescenenode.getTransform().setParent(mainsn.nativescenenode.getTransform());
i++;
}
return mainsn;
}
/**
* 27.12.17: public static, um allgemeingueltig aus einem LoadedMaterial ein Material zu machen. War frueher in LoadedFile.
* 30.12.18: For loading a texture, the model origin (eg. a bundle) and an optional different path is needed. The texture name is taken from the material.
* Also an absolute path in texture name like "bundle:/xx/yy/zz.png" is possible. Then it can be loaded without further information.
* <p>
* Returns mull, wenn bei Texturen Bundle oder Path fehlen. Aufrufer kann DummyMaterial verwenden oder auch keins (wird dann wireframe).
* 13.2.24: Shouldn't need a bundle any more.
*
* @param mat
* @param texturebasepath for bundle and HTTP. Might only be null with absolute texturename. Is relative to resourceloader or absolute path (eg. "engine:cesiumbox").
* @return
*/
public /*10.4.17*/ static /*Native*/Material buildMaterial(ResourceLoader resourceLoader, PortableMaterial mat, ResourcePath texturebasepath, boolean hasnormals) {
NativeMaterial nmat;
//SHADED ist der Defasult
HashMap<NumericType, NumericValue> parameters = new HashMap<NumericType, NumericValue>();
if (!mat.shaded) {
parameters.put(NumericType.SHADING, new NumericValue(NumericValue.UNSHADED));
} else {
if (!hasnormals) {
parameters.put(NumericType.SHADING, new NumericValue(NumericValue.FLAT));
}
}
if (mat.texture != null) {
String texturename = mat.texture;
/*21.12.16 nicht mehr noetig wegen ResourcePath if (texturebasepath == null) {
texturebasepath = ".";
}*/
if (StringUtils.contains(texturename, ":")) {
// use case isn't gltf but manually build model definitions. Is a kind of absolute texture path.
int index = StringUtils.indexOf(texturename, ":");
texturebasepath = null;
// texturename in resourceloader will be replaced later anyway, so just "" is ok.
Bundle bundle = BundleRegistry.getBundle(StringUtils.substring(texturename, 0, index));
if (bundle == null) {
logger.warn("bundle not found:" + StringUtils.substring(texturename, 0, index));
}
resourceLoader = new ResourceLoaderFromBundle(new BundleResource(bundle, null, ""));
texturename = StringUtils.substring(texturename, index + 1);
} else {
if (texturebasepath == null) {
logger.warn("no texturebasepath. Not building material.");
return null;
}
}
Texture texture;
HashMap<String, NativeTexture> map = new HashMap<String, NativeTexture>();
if (resourceLoader != null) {
//BundleResource br = new BundleResource(texturebasepath, texturename);
//br.bundle = bundle;
URL br = resourceLoader.fromRootReference(texturebasepath, texturename).getUrl();
texture = new Texture/*.buildBundleTexture*/(br, mat.wraps, mat.wrapt);
if (texture.texture == null) {
// 13.9.23: Better to log this
logger.warn("failed to build texture from " + texturename + " at " + texturebasepath);
texturename = texturename;
}
map.put("basetex", texture.texture);
} else {
// 26.4.17: resourceLoader muat exist
logger.error("bundle not set");
}
//map.put("normalmap",normalmap.texture);
//TODO die anderen Materialparameter
nmat = Platform.getInstance().buildMaterial(null, null, map, parameters, null);
} else {
HashMap<ColorType, Color> color = new HashMap<ColorType, Color>();
color.put(ColorType.MAIN, mat.color);
//TODO die restlichen colors
// 25.4.19 unshaded wird oben zwar schon eingetragen, aber nicht immer. "shaded" ist eh etwas unklar. Auf jeden Fall bleibt ein Material mit Color in JME sonst schwarz.
//Darum erstmal immer setzen, bis klar ist, was mit Property "shaded" ist. 28.4.19: Das ist aber doof, nur weil JME die combination shaded/ambientLight schwarz darstellt.
//Evtl. wegen Normale?
//parameters.put(NumericType.UNSHADED, new NumericValue(1));
nmat = Platform.getInstance().buildMaterial(null, color, null, parameters, null);
}
return new Material(nmat);
}
/**
* Eine Liste der Materialien EINES Objects anlegen.
* Nur die in den Facelisten des Objekts wirklich verwendeten Materialien anlegen. Sonst stimmt
* die Zuordnung FaceList->Material ueber denselben Index nicht.
* Das Bundle wird zum Finden von Texturen gebraucht.
* 2.5.19: Spaetestens seit Flat Shading ist es noch nicht sicher, wie das Material konkret angelegt werden muss. Darum
* die Matlist nur mit MaterialDefinitionen anlegen
*/
private List<PortableMaterial/*NativeMaterial*/> buildMatlist(/*13.2.24 Bundle bundle,*/ PortableModelDefinition obj, /*MaterialPool matpool,*/ ResourcePath texturebasepath) {
List<PortableMaterial> matlist = new ArrayList<PortableMaterial>();
int index = 0;
for (String matname : obj.geolistmaterial) {
PortableMaterial mat = pml.findMaterial(matname);
//das kann auch null sein. Dann wird später ein Dummy angelegt.
matlist.add(mat);
}
return matlist;
}
/**
* Material, das verwendet wird, wenn das eigentlich definierte nicht bekannt ist.
* Einfach schlicht blau.
* Better white to make more clear its not intended.
*/
private NativeMaterial getDummyMaterial() {
dummymaterialused = true;
if (dummyMaterial == null) {
HashMap<ColorType, Color> color = new HashMap<ColorType, Color>();
color.put(ColorType.MAIN, Color.WHITE);
dummyMaterial = (Platform.getInstance()).buildMaterial(null, color, null, null, null);
}
return dummyMaterial;
}
}
| thomass171/tcp-22 | engine/src/main/java/de/yard/threed/engine/loader/PortableModelBuilder.java | 5,044 | //Evtl. wegen Normale? | line_comment | nl | package de.yard.threed.engine.loader;
import de.yard.threed.core.Color;
import de.yard.threed.core.ColorType;
import de.yard.threed.core.NumericType;
import de.yard.threed.core.NumericValue;
import de.yard.threed.core.StringUtils;
import de.yard.threed.core.loader.PortableMaterial;
import de.yard.threed.core.loader.PortableModelDefinition;
import de.yard.threed.core.loader.PortableModelList;
import de.yard.threed.core.platform.Config;
import de.yard.threed.core.platform.Log;
import de.yard.threed.core.platform.NativeCamera;
import de.yard.threed.core.platform.NativeGeometry;
import de.yard.threed.core.platform.NativeMaterial;
import de.yard.threed.core.platform.NativeTexture;
import de.yard.threed.core.platform.Platform;
import de.yard.threed.core.resource.Bundle;
import de.yard.threed.core.resource.BundleRegistry;
import de.yard.threed.core.resource.BundleResource;
import de.yard.threed.core.resource.NativeResource;
import de.yard.threed.core.resource.ResourceLoader;
import de.yard.threed.core.resource.ResourcePath;
import de.yard.threed.core.geometry.SimpleGeometry;
import de.yard.threed.core.resource.URL;
import de.yard.threed.engine.GenericGeometry;
import de.yard.threed.engine.Material;
import de.yard.threed.engine.Mesh;
import de.yard.threed.engine.PerspectiveCamera;
import de.yard.threed.engine.SceneNode;
import de.yard.threed.engine.Texture;
import de.yard.threed.engine.platform.EngineHelper;
import de.yard.threed.engine.platform.ResourceLoaderFromBundle;
import de.yard.threed.engine.platform.common.AbstractSceneRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 06.12.22: A builder for universal model specification.
*/
public class PortableModelBuilder {
static Log logger = Platform.getInstance().getLog(PortableModelBuilder.class);
// Material, das verwendet wird, wenn das eigentlich definierte nicht bekannt ist
private NativeMaterial dummyMaterial;
//ResourcePath defaulttexturebasepath;
PortableModelList pml;
//Just an indicator for testing
public boolean dummymaterialused;
public PortableModelBuilder(PortableModelList pml) {
this.pml = pml;
}
/*public PortableModelBuilder(ResourcePath texturebasepath, List<GeoMat> gml) {
this.defaulttexturebasepath = texturebasepath;
this.gml = gml;
/*TODO erstmal material in gltf klaeren for (GeoMat gm : gml){
PreprocessedLoadedObject ppo = new PreprocessedLoadedObject();
ppo.geolist=new ArrayList<SimpleGeometry>();
ppo.geolist.add(gm.geo);
objects.add(ppo);
LoadedMaterial ppm = new LoadedMaterial();
ppm.
materials.add(ppm);
}* /
}*/
/**
* ResourceLoader is needed in builder for loading textures.
* <p>
* alttexturepath might be null. Then texturebasepath is used.
*
* @return
*/
public SceneNode buildModel(ResourceLoader resourceLoader) {
return buildModel(resourceLoader, null);
}
public SceneNode buildModel(ResourceLoader resourceLoader, ResourcePath alttexturepath) {
SceneNode rootnode = new SceneNode();
if (pml.getName() != null) {
rootnode.setName(pml.getName());
}
for (int i = 0; i < pml.getObjectCount(); i++) {
SceneNode newModel = buildModel(resourceLoader, pml.getObject(i), alttexturepath);
String parent = pml.getParent(i);
SceneNode destinationNode = rootnode;
if (parent != null) {
logger.debug("looking for parent " + parent);
NativeCamera camera = AbstractSceneRunner.getInstance().findCameraByName(parent);
PerspectiveCamera perspectiveCamera = new PerspectiveCamera(camera);
destinationNode = perspectiveCamera.getCarrier();
// attach to carrier will propagate layer. newModel.getTransform().setLayer(perspectiveCamera.getLayer());
logger.debug("found parent camera with layer " + perspectiveCamera.getLayer());
}
destinationNode.attach(newModel);
}
return rootnode;
}
private SceneNode buildModel(ResourceLoader resourceLoader, PortableModelDefinition obj, ResourcePath alttexturepath/*, boolean dummywegensignatureindeutigkeit*/) {
//this.bundle = bundle;
//this.rpath = rpath;
ResourcePath nr = pml.defaulttexturebasepath;
if (alttexturepath != null) {
nr = alttexturepath;
}
return buildObject(resourceLoader, obj /*, null/*, matlist*/, nr);
}
private SceneNode buildObject(ResourceLoader resourceLoader, PortableModelDefinition obj, /*MaterialPool matpool,*/ ResourcePath texturebasepath) {
/*30.12.17 Es kann mit GLTF auch leere Objekte geben if (obj.geolist == null) {
throw new RuntimeException("geo not preprocessed");
}*/
// Eine Liste der Materialien DIESES Objects anlegen.
// Nur die in den Facelisten des Objekts wirklich verwendeten Materialien anlegen. Sonst stimmt
// die Zuordnung nicht. 2.5.19: Spaetestens seit Flat Shading ist es noch nicht sicher, wie das Material konkret angelegt werden muss. Darum
// die Matlist nur mit MaterialDefinitionen anlegen.
// 2.5.19: matpool: aknn man sicher sein, dass es wirklich dasselbe ist? Z.B (un/flat)shaded. Eigentlich ist es doch ein zugrosses Risiko im Vergleich zum Nutzen, oder?
// mal weglassen
/*30.12.17: das pruef ich auch nicht mehr
if (obj.geolistmaterial.size() == 0) {
// Kommt wolh bei RollerCoaster.ac schon mal vor.
logger.warn("facelistmaterial isType empty in " + obj.name);
}*/
List<PortableMaterial/*NativeMaterial*/> matlist = buildMatlist(/*13.2.24 bundle,*/ obj, /*matpool,*/ texturebasepath);
boolean wireframe = false;
if (wireframe) {
for (int i = 0; i < matlist.size(); i++) {
matlist.set(i, null);
}
}
SceneNode model = new SceneNode();
String name;
if (StringUtils.empty(obj.name)) {
name = "<no name>";
} else {
name = obj.name;
}
model.setName(name);
if (obj.translation != null) {
model.getTransform().setPosition((obj.translation));
}
if (obj.rotation != null) {
model.getTransform().setRotation((obj.rotation));
}
// Keine leeren Objekte anlegen (z.B. AC World). Als Node aber schon. Die AC kids Hierarchie soll erhalten bleiben.
if (obj.geolist != null && obj.geolist.size() > 0) {
if (obj.geolist.size() > 1/*faces.size() > 1 && matlist.size() > 1*/) {
//List<SimpleGeometry> geolist = GeometryHelper.prepareGeometry(obj.vertices, obj.faces, /*matlist,*/ null, true, obj.crease);
//2.5.19: Gibt es das seit GLTF ueberhauot noch? Ja, eine Node kann doch mehrere Meshes haben, oder?
SceneNode m = buildSceneNode(resourceLoader, obj.geolist, matlist, false, false, texturebasepath/*3.5.19, obj.texture*/);
m.setName(obj.name);
model.attach(m);
} else {
//List<SimpleGeometry> geolist = GeometryHelper.prepareGeometry(obj.vertices, obj.faces, /*matlist,*/ null, false, obj.crease);
//if (geolist.size() > 1) {
// throw new RuntimeException("unexpected multiple geos");
//}
if (obj.geolist.size() == 0) {
logger.error("no geo list");
}
PortableMaterial/*NativeMaterial*/ mate = null;
if (matlist.size() == 0) {
logger.error("no matlist in " + obj.name);
} else {
mate = matlist.get(0);
}
//2.5.19: Neu an dieser Stelle
NativeMaterial nmat = buildMaterialFromPortableMaterial(resourceLoader, mate, texturebasepath, /*3.5.19obj.texture, */obj.geolist.get(0).getNormals() != null);
Mesh mesh = new Mesh(new GenericGeometry(obj.geolist.get(0)).getNativeGeometry(), nmat/*mate*/, false, false);
model.setMesh(mesh);
}
}
for (int i = 0; i < obj.kids.size(); i++) {
model.attach(buildObject(resourceLoader, obj.kids.get(i)/*, matpool/*, matlist*/, texturebasepath));
}
if (Config.modelloaddebuglog) {
logger.debug("buildObject complete " + name);
}
return model;
}
NativeMaterial buildMaterialFromPortableMaterial(ResourceLoader resourceLoader, /*Bundle bundle,*/ PortableMaterial portableMaterial, ResourcePath texturebasepath/*3.5.19, String objtexture*/, boolean hasnormals) {
NativeMaterial nmat;
if (portableMaterial != null) {
//Auf AC zugeschnitten, denn nur die(?) haben die Textur am Object.
//22.12.17: Darum jetzt bevorzugt den Texturename aus dem Material.
Material ma = /*PortableMaterial.*/buildMaterial(/*bundle*/resourceLoader, portableMaterial, /*3.5.19(portableMaterial.texture != null) ? * 14.2.24 /portableMaterial.texture/*3.5.19 : objtexture*/ texturebasepath, hasnormals);
if (ma == null) {
logger.warn("No material. Using dummy material.");
nmat = getDummyMaterial();
} else {
nmat = ma.material;
}
} else {
nmat = getDummyMaterial();
}
return nmat;
}
/**
* Teil einer fruehere Platform.buildMeshG() Methode.
* 10.3.16: Da auch WebGl und Opengl keine multiple material koennen, den extract aus JME hierauf gezogen. Auch weil es erstmal ganz gut funktioniert.
* 02.05.16: Im Sinne der Vereinfachung generell keine multiple material vorsehen, auch wenn Unity es kann. Die Engine extrahiert jetzt Submeshes.
* Ist in Model statt in Mesh, weil durch die Aufsplittung ja auch ein Model rauskommt. Die Methode ist jetzt auch wirklich nur fuer Multi Material gedacht.
* 2.5.19: War mal Constructor von SceneNode. Passt da aber nicht hin.
*/
public SceneNode buildSceneNode(ResourceLoader resourceLoader, /*Bundle bundle,*/ List<SimpleGeometry> geolist, List<PortableMaterial> material, boolean castShadow, boolean receiveShadow, ResourcePath texturebasepath/*3.5.19, String objtexture*/) {
//this();
SceneNode mainsn = new SceneNode();
int i = 0;
for (SimpleGeometry geo : geolist) {
NativeGeometry ng = EngineHelper.buildGeometry(geo.getVertices(), /*new SmartArrayList<Face3List>(*/geo.getIndices(), geo.getUvs(), geo.getNormals());
//2.5.19: Neu an dieser Stelle
NativeMaterial nmat = buildMaterialFromPortableMaterial(resourceLoader, material.get(i), texturebasepath, /*3.5.19objtexture,*/ geo.getNormals() != null);
Mesh submesh = new Mesh(ng, nmat/*material.get(i)*/, castShadow, receiveShadow);
// add(new SceneNode(submesh));
SceneNode sn = new SceneNode(submesh);
sn.nativescenenode.getTransform().setParent(mainsn.nativescenenode.getTransform());
i++;
}
return mainsn;
}
/**
* 27.12.17: public static, um allgemeingueltig aus einem LoadedMaterial ein Material zu machen. War frueher in LoadedFile.
* 30.12.18: For loading a texture, the model origin (eg. a bundle) and an optional different path is needed. The texture name is taken from the material.
* Also an absolute path in texture name like "bundle:/xx/yy/zz.png" is possible. Then it can be loaded without further information.
* <p>
* Returns mull, wenn bei Texturen Bundle oder Path fehlen. Aufrufer kann DummyMaterial verwenden oder auch keins (wird dann wireframe).
* 13.2.24: Shouldn't need a bundle any more.
*
* @param mat
* @param texturebasepath for bundle and HTTP. Might only be null with absolute texturename. Is relative to resourceloader or absolute path (eg. "engine:cesiumbox").
* @return
*/
public /*10.4.17*/ static /*Native*/Material buildMaterial(ResourceLoader resourceLoader, PortableMaterial mat, ResourcePath texturebasepath, boolean hasnormals) {
NativeMaterial nmat;
//SHADED ist der Defasult
HashMap<NumericType, NumericValue> parameters = new HashMap<NumericType, NumericValue>();
if (!mat.shaded) {
parameters.put(NumericType.SHADING, new NumericValue(NumericValue.UNSHADED));
} else {
if (!hasnormals) {
parameters.put(NumericType.SHADING, new NumericValue(NumericValue.FLAT));
}
}
if (mat.texture != null) {
String texturename = mat.texture;
/*21.12.16 nicht mehr noetig wegen ResourcePath if (texturebasepath == null) {
texturebasepath = ".";
}*/
if (StringUtils.contains(texturename, ":")) {
// use case isn't gltf but manually build model definitions. Is a kind of absolute texture path.
int index = StringUtils.indexOf(texturename, ":");
texturebasepath = null;
// texturename in resourceloader will be replaced later anyway, so just "" is ok.
Bundle bundle = BundleRegistry.getBundle(StringUtils.substring(texturename, 0, index));
if (bundle == null) {
logger.warn("bundle not found:" + StringUtils.substring(texturename, 0, index));
}
resourceLoader = new ResourceLoaderFromBundle(new BundleResource(bundle, null, ""));
texturename = StringUtils.substring(texturename, index + 1);
} else {
if (texturebasepath == null) {
logger.warn("no texturebasepath. Not building material.");
return null;
}
}
Texture texture;
HashMap<String, NativeTexture> map = new HashMap<String, NativeTexture>();
if (resourceLoader != null) {
//BundleResource br = new BundleResource(texturebasepath, texturename);
//br.bundle = bundle;
URL br = resourceLoader.fromRootReference(texturebasepath, texturename).getUrl();
texture = new Texture/*.buildBundleTexture*/(br, mat.wraps, mat.wrapt);
if (texture.texture == null) {
// 13.9.23: Better to log this
logger.warn("failed to build texture from " + texturename + " at " + texturebasepath);
texturename = texturename;
}
map.put("basetex", texture.texture);
} else {
// 26.4.17: resourceLoader muat exist
logger.error("bundle not set");
}
//map.put("normalmap",normalmap.texture);
//TODO die anderen Materialparameter
nmat = Platform.getInstance().buildMaterial(null, null, map, parameters, null);
} else {
HashMap<ColorType, Color> color = new HashMap<ColorType, Color>();
color.put(ColorType.MAIN, mat.color);
//TODO die restlichen colors
// 25.4.19 unshaded wird oben zwar schon eingetragen, aber nicht immer. "shaded" ist eh etwas unklar. Auf jeden Fall bleibt ein Material mit Color in JME sonst schwarz.
//Darum erstmal immer setzen, bis klar ist, was mit Property "shaded" ist. 28.4.19: Das ist aber doof, nur weil JME die combination shaded/ambientLight schwarz darstellt.
//Evtl. wegen<SUF>
//parameters.put(NumericType.UNSHADED, new NumericValue(1));
nmat = Platform.getInstance().buildMaterial(null, color, null, parameters, null);
}
return new Material(nmat);
}
/**
* Eine Liste der Materialien EINES Objects anlegen.
* Nur die in den Facelisten des Objekts wirklich verwendeten Materialien anlegen. Sonst stimmt
* die Zuordnung FaceList->Material ueber denselben Index nicht.
* Das Bundle wird zum Finden von Texturen gebraucht.
* 2.5.19: Spaetestens seit Flat Shading ist es noch nicht sicher, wie das Material konkret angelegt werden muss. Darum
* die Matlist nur mit MaterialDefinitionen anlegen
*/
private List<PortableMaterial/*NativeMaterial*/> buildMatlist(/*13.2.24 Bundle bundle,*/ PortableModelDefinition obj, /*MaterialPool matpool,*/ ResourcePath texturebasepath) {
List<PortableMaterial> matlist = new ArrayList<PortableMaterial>();
int index = 0;
for (String matname : obj.geolistmaterial) {
PortableMaterial mat = pml.findMaterial(matname);
//das kann auch null sein. Dann wird später ein Dummy angelegt.
matlist.add(mat);
}
return matlist;
}
/**
* Material, das verwendet wird, wenn das eigentlich definierte nicht bekannt ist.
* Einfach schlicht blau.
* Better white to make more clear its not intended.
*/
private NativeMaterial getDummyMaterial() {
dummymaterialused = true;
if (dummyMaterial == null) {
HashMap<ColorType, Color> color = new HashMap<ColorType, Color>();
color.put(ColorType.MAIN, Color.WHITE);
dummyMaterial = (Platform.getInstance()).buildMaterial(null, color, null, null, null);
}
return dummyMaterial;
}
}
|
44073_47 | package de.yard.threed.flightgear.core.simgear.scene.tgdb;
import de.yard.threed.core.GeneralParameterHandler;
import de.yard.threed.core.geometry.SimpleGeometry;
import de.yard.threed.core.loader.AbstractLoader;
import de.yard.threed.core.loader.InvalidDataException;
import de.yard.threed.core.loader.LoaderGLTF;
import de.yard.threed.core.loader.PortableMaterial;
import de.yard.threed.core.loader.PortableModelDefinition;
import de.yard.threed.core.loader.PortableModelList;
import de.yard.threed.core.platform.Platform;
import de.yard.threed.core.resource.BundleResource;
import de.yard.threed.engine.platform.ResourceLoaderFromBundle;
import de.yard.threed.flightgear.LoaderOptions;
import de.yard.threed.core.Vector3;
import de.yard.threed.flightgear.core.osg.Group;
import de.yard.threed.flightgear.core.osg.Node;
import de.yard.threed.flightgear.core.simgear.scene.material.EffectGeode;
import de.yard.threed.flightgear.core.simgear.scene.material.FGEffect;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterial;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterialCache;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterialLib;
import de.yard.threed.flightgear.core.simgear.scene.util.SGReaderWriterOptions;
import de.yard.threed.flightgear.core.simgear.geodesy.SGGeod;
import de.yard.threed.flightgear.LoaderBTG;
import de.yard.threed.core.platform.Log;
import de.yard.threed.core.resource.BundleData;
import de.yard.threed.core.buffer.ByteArrayInputStream;
import de.yard.threed.core.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* From obj.cxx
* 30.9.23: Methods no longer static.
* <p/>
* Created by thomass on 04.08.16.
*/
public class Obj {
Log logger = Platform.getInstance().getLog(Obj.class);
public List<String> foundMaterial = new ArrayList<String>();
public List<String> notFoundMaterial = new ArrayList<String>();
/**
* Resource muss Bundle mit path der resource enthalten.
* Bundle muss schon geladen sein. Suffix ".gz" darf nicht mit angegeben werden.
* 14.12.17: Wegen preprocess zerlegt in alten SGLoadBTG und neuen SGbuildBTG.
* 15.2.24: Now async
* @return
*/
public void/*Node*/ SGLoadBTG(BundleResource bpath, SGReaderWriterOptions options, LoaderOptions boptions, GeneralParameterHandler<Node> delegate) {
SGLoadBTG(bpath, options, boptions, 222, new GeneralParameterHandler<PortableModelList>() {
@Override
public void handle(PortableModelList ppfile) {
if (ppfile == null) {
//already logged
return ;
}
Node node = SGbuildBTG(ppfile, boptions != null ? boptions.materialLib : null);
delegate.handle(node);
}
});
}
/**
* Runs sync. Bundle must have been loaded already.
* 15.2.14: No longer sync but asnyc like LoaderGLTF.
*/
public void /*PortableModelList/*Node*/ SGLoadBTG(BundleResource bpath, SGReaderWriterOptions options, LoaderOptions boptions, int dummy, GeneralParameterHandler<PortableModelList> delegate) {
//tsch_log("obj.cxx::SGLoadBTG(%d) path=%s \n",0,path.c_str());
/*SGBinObject*/
AbstractLoader tile=null;
//if (!tile.read_bin(path))
// return NULL;
if (bpath == null) {
throw new RuntimeException("bpath is null");
//tile = (LoaderBTG) ModelFactory.readModel(new FileSystemResource(path));
} else {
//TODO ueber platform. 21.12.17: NeeNee. Ich lad mal direkt das btg.
// Auch mit GLTF ist das Laden ueber die Platform so einfach nicht möglich, weil eine Sonderbehandlung fuer das Material/Landclasses
// erforderlich ist. Daher erstmal weiterhin hier das Model bauen.
//LoadResult lr = ModelLoader.readModelFromBundle(bpath, false);
if (bpath.bundle == null) {
logger.warn("no bundle set");
return /*null*/;
}
if (boptions != null && boptions.usegltf) {
BundleData ins = null;
String basename = StringUtils.substringBeforeLast(bpath.getFullName(), ".btg");
bpath = new BundleResource(bpath.bundle, basename + ".gltf");
ins = bpath.bundle.getResource(bpath);
if (ins == null) {
logger.error(bpath.getName() + " not found in bundle " + bpath);
return /*null*/;
}
LoaderGLTF.load(new ResourceLoaderFromBundle(bpath), delegate);
} else {
//load from BTG
BundleData ins = null;
// special handling of btg.gz files. Irgendwie Driss
// 12.6.17: Andererseits werden pp files hier auch transparent geladen. Aber das macht eh schon der Bundleloader, damit der unzip in der platform ist.
ins = bpath.bundle.getResource(bpath);
if (ins == null) {
logger.error("loadModel " + bpath.getName() + " not found in bundle " + bpath);
return /*null*/;
}
try {
tile = new LoaderBTG(new ByteArrayInputStream(ins.b), options, boptions, bpath.getFullName());
} catch (InvalidDataException e) {
throw new RuntimeException(e);
}
// Code moved to LoaderBTG.preProcess();
PortableModelList ppfile = tile.preProcess();
//ppfile.btgcenter = ((LoaderBTG)tile).center;
delegate.handle(ppfile);
}
//21.12.17 tile = (LoaderBTG) lr.loader;
}
//return ppfile;
}
/**
* 18.4.19: matlib is optional. Without it will be wireframe.
*
* @return
*/
public Node SGbuildBTG(PortableModelList ppfile, SGMaterialLib matlib) {
boolean simplifyDistant = false;
boolean simplifyNear = false;
boolean useVBOs = false;
Vector3 center = (ppfile.getObject(0).translation);
SGMaterialCache matcache = null;
if (matlib != null) {
matcache = matlib.generateMatCache(SGGeod.fromCart(center));
}
//18.4.19: Mesh isType build in getSurfaceGeometryPart2 with material from matcache.
//The GLTF itself does not contain material.
Node node = getSurfaceGeometryPart2(ppfile/*.gml*/, useVBOs, matcache);
if (node != null && simplifyDistant) {
//osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
//node->accept(simplifier);
}
// The toplevel transform for that tile.
/*osg::MatrixTransform* transform = new osg::MatrixTransform;
transform->setName(path);
transform->setMatrix(osg::Matrix::setRotateStatus(toOsg(hlOr))*
osg::Matrix::translate(toOsg(center)));*/
Group transform = new Group();
//24.1.19: Der "name" wird in der Hierarchie dann doppelt sein, oder?
transform.setName(ppfile.getName());
//transform.getTransform().setPosition(ppfile.btgcenter);
transform.getTransform().setPosition(center);
if (node != null) {
// tile points
/*SGTileDetailsCallback* tileDetailsCallback = new SGTileDetailsCallback;
tileDetailsCallback->insertPtGeometry( tile, matcache );
// PagedLOD for the random objects so we don't need to generate
// them all on tile loading.
osg::PagedLOD* pagedLOD = new osg::PagedLOD;
pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
pagedLOD->setName("pagedObjectLOD");*/
if (simplifyNear == simplifyDistant) {
// Same terrain type isType used for both near and far distances,
// so add it to the main group.
Group terrainGroup = new Group();
terrainGroup.setName("BTGTerrainGroup");
terrainGroup.attach(node);
transform.attach(terrainGroup);
} else if (simplifyDistant) {
// Simplified terrain isType only used in the distance, the
// call-back below will re-generate the closer version
//TODO pagedLOD.addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
}
/* osg::ref_ptr<SGReaderWriterOptions> opt;
opt = SGReaderWriterOptions::copyOrCreate(options);
// we just need to know about the read file callback that itself holds the data
tileDetailsCallback->_options = opt;
tileDetailsCallback->_path = std::string(path);
tileDetailsCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
tileDetailsCallback->_gbs_center = center;
tileDetailsCallback->_rootNode = node;
tileDetailsCallback->_randomSurfaceLightsComputed = false;
tileDetailsCallback->_tileRandomObjectsComputed = false;
osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
callbackOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL);
callbackOptions->setReadFileCallback(tileDetailsCallback);
pagedLOD->setDatabaseOptions(callbackOptions.get());
// Ensure that the random objects aren't expired too quickly
pagedLOD->setMinimumExpiryTime(pagedLOD->getNumChildren(), tile_min_expiry);
pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy filename for random objects callback");
pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
transform->addChild(pagedLOD);*/
}
//transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
return transform;
}
/**
* Aus der allen Trianglemaps ein Mesh erstellen.
* 12.12.17: Aufgeteilt um das erstellen der Geo im preprocess verwenden zu koennen.
* 18.04.2019: ppfile contains no material. matcache is "optional". If null, wireframe will be created.
* 30.9.23: Moved here from SGTileGeometryBin.
*/
public Node getSurfaceGeometryPart2(/*List<GeoMat> geos*/PortableModelList ppfile, boolean useVBOs, SGMaterialCache matcache) {
if (ppfile.getObjectCount() == 0)
return null;
EffectGeode eg = null;
//27.12.17:zur Vereinfachung immer group anlegen
Group group = new Group();//(ppfile.objects.size() > 1 ? new Group() : null);
if (group != null) {
group.setName("surfaceGeometryGroup");
}
//osg::Geode* geode = new osg::Geode;
//SGMaterialTriangleMap::const_iterator i;
//for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
//for (String ii : materialTriangleMap.keySet()) {
for (int k = 0; k < ppfile.getObjectCount(); k++) {
PortableModelDefinition po = ppfile.getObject(k);
for (int index = 0; index < po.geolist.size(); index++) {
SimpleGeometry p = po.geolist.get(index);
/*in Part1 SGTexturedTriangleBin i = materialTriangleMap.get(ii);
SimpleGeometry geometry = i/*->getSecond* /.buildGeometry(useVBOs);
SGMaterial mat = null;
if (matcache != null) {
mat = matcache.find(ii/*->getFirst* /);
}*/
PortableMaterial mat=null;
String matname = po.geolistmaterial.get(index);
// matcache should be available, otherwise there will no material later very likely. (wireframe)
if (ppfile.materials.size() == 0 && matcache != null) {
SGMaterial sgmat = matcache.find(matname);
//31.12.17: TODO textureindx mal klaeren!
//5.10.23: TODO use getEffectMaterialByTextureIndex
int textureindex = 0;
FGEffect oneEffect = sgmat.get_one_effect(textureindex);
if (oneEffect == null) {
logger.warn("No effect available at " + textureindex + " for " + matname);
}else {
mat = (sgmat != null) ? (oneEffect.getMaterialDefinition()) :null;
}
} else {
mat = ppfile.findMaterial(matname);
}
// FG-DIFF
// Zu FG abweichende implementierung. Wenn es kein Material gibt, wireframe setzen. Fuer Testen vielleicht ganz gut. Ob auf Dauer auch?
// In FG wird das Material ueber Effect in EffectGeode (teilweise ueber Callback) abgebildet. Effect verbindet direkt zum Shader.
// Darueber wird zumindest wohl die Textur definiert. Hier jetzt das Mesh direkt erzeugen.
eg = new EffectGeode();
// FG-DIFF immer derselbe Name ist doch bloed. Es ist auch nicht erkennbar, dass FG da Logik dran hat. 12.12.17: Tja, jetzt hab ich aber keinen Namen.
//eg.setName("EffectGeode");
eg.setName(po.name);// + ii+"("+i.getNumTriangles()+" tris)");
if (mat != null) {
//12.12.17: im Effect ist das "endgültige" Material enthalten. Der EffectGeode treagt dazu nichts bei, zumindest nichts bekanntes.
//Darum kommt jetzt auch nur noch "echtes" Material rein (wegen preprocess)
eg.material = mat;
//eg.setMaterial(p.mat);
//Effect e = p.mat.get_one_effect(p.textureindex);///*->getSecond*/.getTextureIndex()));
//eg.setEffect(e);
foundMaterial.add(matname);
} else {
// 31.12.17 das log ich mal als warning, weils wirklich ein Grund zur Warnung ist
// 18.04.19 das wird dann halt wireframe
logger.warn("no material " + matname + " found");
eg.setMaterial(null);
notFoundMaterial.add(matname);
}
//eg.addDrawable(geometry);
//eg.runGenerators(geometry); // Generate extra data needed by effect
if (group != null) {
group.attach(eg);
}
eg.buildMesh(p/*.geo*/);
}
}
if (group != null) {
return group;
} else {
return eg;
}
}
}
| thomass171/tcp-flightgear | flightgear/src/main/java/de/yard/threed/flightgear/core/simgear/scene/tgdb/Obj.java | 4,249 | //Effect e = p.mat.get_one_effect(p.textureindex);///*->getSecond*/.getTextureIndex())); | line_comment | nl | package de.yard.threed.flightgear.core.simgear.scene.tgdb;
import de.yard.threed.core.GeneralParameterHandler;
import de.yard.threed.core.geometry.SimpleGeometry;
import de.yard.threed.core.loader.AbstractLoader;
import de.yard.threed.core.loader.InvalidDataException;
import de.yard.threed.core.loader.LoaderGLTF;
import de.yard.threed.core.loader.PortableMaterial;
import de.yard.threed.core.loader.PortableModelDefinition;
import de.yard.threed.core.loader.PortableModelList;
import de.yard.threed.core.platform.Platform;
import de.yard.threed.core.resource.BundleResource;
import de.yard.threed.engine.platform.ResourceLoaderFromBundle;
import de.yard.threed.flightgear.LoaderOptions;
import de.yard.threed.core.Vector3;
import de.yard.threed.flightgear.core.osg.Group;
import de.yard.threed.flightgear.core.osg.Node;
import de.yard.threed.flightgear.core.simgear.scene.material.EffectGeode;
import de.yard.threed.flightgear.core.simgear.scene.material.FGEffect;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterial;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterialCache;
import de.yard.threed.flightgear.core.simgear.scene.material.SGMaterialLib;
import de.yard.threed.flightgear.core.simgear.scene.util.SGReaderWriterOptions;
import de.yard.threed.flightgear.core.simgear.geodesy.SGGeod;
import de.yard.threed.flightgear.LoaderBTG;
import de.yard.threed.core.platform.Log;
import de.yard.threed.core.resource.BundleData;
import de.yard.threed.core.buffer.ByteArrayInputStream;
import de.yard.threed.core.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* From obj.cxx
* 30.9.23: Methods no longer static.
* <p/>
* Created by thomass on 04.08.16.
*/
public class Obj {
Log logger = Platform.getInstance().getLog(Obj.class);
public List<String> foundMaterial = new ArrayList<String>();
public List<String> notFoundMaterial = new ArrayList<String>();
/**
* Resource muss Bundle mit path der resource enthalten.
* Bundle muss schon geladen sein. Suffix ".gz" darf nicht mit angegeben werden.
* 14.12.17: Wegen preprocess zerlegt in alten SGLoadBTG und neuen SGbuildBTG.
* 15.2.24: Now async
* @return
*/
public void/*Node*/ SGLoadBTG(BundleResource bpath, SGReaderWriterOptions options, LoaderOptions boptions, GeneralParameterHandler<Node> delegate) {
SGLoadBTG(bpath, options, boptions, 222, new GeneralParameterHandler<PortableModelList>() {
@Override
public void handle(PortableModelList ppfile) {
if (ppfile == null) {
//already logged
return ;
}
Node node = SGbuildBTG(ppfile, boptions != null ? boptions.materialLib : null);
delegate.handle(node);
}
});
}
/**
* Runs sync. Bundle must have been loaded already.
* 15.2.14: No longer sync but asnyc like LoaderGLTF.
*/
public void /*PortableModelList/*Node*/ SGLoadBTG(BundleResource bpath, SGReaderWriterOptions options, LoaderOptions boptions, int dummy, GeneralParameterHandler<PortableModelList> delegate) {
//tsch_log("obj.cxx::SGLoadBTG(%d) path=%s \n",0,path.c_str());
/*SGBinObject*/
AbstractLoader tile=null;
//if (!tile.read_bin(path))
// return NULL;
if (bpath == null) {
throw new RuntimeException("bpath is null");
//tile = (LoaderBTG) ModelFactory.readModel(new FileSystemResource(path));
} else {
//TODO ueber platform. 21.12.17: NeeNee. Ich lad mal direkt das btg.
// Auch mit GLTF ist das Laden ueber die Platform so einfach nicht möglich, weil eine Sonderbehandlung fuer das Material/Landclasses
// erforderlich ist. Daher erstmal weiterhin hier das Model bauen.
//LoadResult lr = ModelLoader.readModelFromBundle(bpath, false);
if (bpath.bundle == null) {
logger.warn("no bundle set");
return /*null*/;
}
if (boptions != null && boptions.usegltf) {
BundleData ins = null;
String basename = StringUtils.substringBeforeLast(bpath.getFullName(), ".btg");
bpath = new BundleResource(bpath.bundle, basename + ".gltf");
ins = bpath.bundle.getResource(bpath);
if (ins == null) {
logger.error(bpath.getName() + " not found in bundle " + bpath);
return /*null*/;
}
LoaderGLTF.load(new ResourceLoaderFromBundle(bpath), delegate);
} else {
//load from BTG
BundleData ins = null;
// special handling of btg.gz files. Irgendwie Driss
// 12.6.17: Andererseits werden pp files hier auch transparent geladen. Aber das macht eh schon der Bundleloader, damit der unzip in der platform ist.
ins = bpath.bundle.getResource(bpath);
if (ins == null) {
logger.error("loadModel " + bpath.getName() + " not found in bundle " + bpath);
return /*null*/;
}
try {
tile = new LoaderBTG(new ByteArrayInputStream(ins.b), options, boptions, bpath.getFullName());
} catch (InvalidDataException e) {
throw new RuntimeException(e);
}
// Code moved to LoaderBTG.preProcess();
PortableModelList ppfile = tile.preProcess();
//ppfile.btgcenter = ((LoaderBTG)tile).center;
delegate.handle(ppfile);
}
//21.12.17 tile = (LoaderBTG) lr.loader;
}
//return ppfile;
}
/**
* 18.4.19: matlib is optional. Without it will be wireframe.
*
* @return
*/
public Node SGbuildBTG(PortableModelList ppfile, SGMaterialLib matlib) {
boolean simplifyDistant = false;
boolean simplifyNear = false;
boolean useVBOs = false;
Vector3 center = (ppfile.getObject(0).translation);
SGMaterialCache matcache = null;
if (matlib != null) {
matcache = matlib.generateMatCache(SGGeod.fromCart(center));
}
//18.4.19: Mesh isType build in getSurfaceGeometryPart2 with material from matcache.
//The GLTF itself does not contain material.
Node node = getSurfaceGeometryPart2(ppfile/*.gml*/, useVBOs, matcache);
if (node != null && simplifyDistant) {
//osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
//node->accept(simplifier);
}
// The toplevel transform for that tile.
/*osg::MatrixTransform* transform = new osg::MatrixTransform;
transform->setName(path);
transform->setMatrix(osg::Matrix::setRotateStatus(toOsg(hlOr))*
osg::Matrix::translate(toOsg(center)));*/
Group transform = new Group();
//24.1.19: Der "name" wird in der Hierarchie dann doppelt sein, oder?
transform.setName(ppfile.getName());
//transform.getTransform().setPosition(ppfile.btgcenter);
transform.getTransform().setPosition(center);
if (node != null) {
// tile points
/*SGTileDetailsCallback* tileDetailsCallback = new SGTileDetailsCallback;
tileDetailsCallback->insertPtGeometry( tile, matcache );
// PagedLOD for the random objects so we don't need to generate
// them all on tile loading.
osg::PagedLOD* pagedLOD = new osg::PagedLOD;
pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
pagedLOD->setName("pagedObjectLOD");*/
if (simplifyNear == simplifyDistant) {
// Same terrain type isType used for both near and far distances,
// so add it to the main group.
Group terrainGroup = new Group();
terrainGroup.setName("BTGTerrainGroup");
terrainGroup.attach(node);
transform.attach(terrainGroup);
} else if (simplifyDistant) {
// Simplified terrain isType only used in the distance, the
// call-back below will re-generate the closer version
//TODO pagedLOD.addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
}
/* osg::ref_ptr<SGReaderWriterOptions> opt;
opt = SGReaderWriterOptions::copyOrCreate(options);
// we just need to know about the read file callback that itself holds the data
tileDetailsCallback->_options = opt;
tileDetailsCallback->_path = std::string(path);
tileDetailsCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
tileDetailsCallback->_gbs_center = center;
tileDetailsCallback->_rootNode = node;
tileDetailsCallback->_randomSurfaceLightsComputed = false;
tileDetailsCallback->_tileRandomObjectsComputed = false;
osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
callbackOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL);
callbackOptions->setReadFileCallback(tileDetailsCallback);
pagedLOD->setDatabaseOptions(callbackOptions.get());
// Ensure that the random objects aren't expired too quickly
pagedLOD->setMinimumExpiryTime(pagedLOD->getNumChildren(), tile_min_expiry);
pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy filename for random objects callback");
pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
transform->addChild(pagedLOD);*/
}
//transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
return transform;
}
/**
* Aus der allen Trianglemaps ein Mesh erstellen.
* 12.12.17: Aufgeteilt um das erstellen der Geo im preprocess verwenden zu koennen.
* 18.04.2019: ppfile contains no material. matcache is "optional". If null, wireframe will be created.
* 30.9.23: Moved here from SGTileGeometryBin.
*/
public Node getSurfaceGeometryPart2(/*List<GeoMat> geos*/PortableModelList ppfile, boolean useVBOs, SGMaterialCache matcache) {
if (ppfile.getObjectCount() == 0)
return null;
EffectGeode eg = null;
//27.12.17:zur Vereinfachung immer group anlegen
Group group = new Group();//(ppfile.objects.size() > 1 ? new Group() : null);
if (group != null) {
group.setName("surfaceGeometryGroup");
}
//osg::Geode* geode = new osg::Geode;
//SGMaterialTriangleMap::const_iterator i;
//for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
//for (String ii : materialTriangleMap.keySet()) {
for (int k = 0; k < ppfile.getObjectCount(); k++) {
PortableModelDefinition po = ppfile.getObject(k);
for (int index = 0; index < po.geolist.size(); index++) {
SimpleGeometry p = po.geolist.get(index);
/*in Part1 SGTexturedTriangleBin i = materialTriangleMap.get(ii);
SimpleGeometry geometry = i/*->getSecond* /.buildGeometry(useVBOs);
SGMaterial mat = null;
if (matcache != null) {
mat = matcache.find(ii/*->getFirst* /);
}*/
PortableMaterial mat=null;
String matname = po.geolistmaterial.get(index);
// matcache should be available, otherwise there will no material later very likely. (wireframe)
if (ppfile.materials.size() == 0 && matcache != null) {
SGMaterial sgmat = matcache.find(matname);
//31.12.17: TODO textureindx mal klaeren!
//5.10.23: TODO use getEffectMaterialByTextureIndex
int textureindex = 0;
FGEffect oneEffect = sgmat.get_one_effect(textureindex);
if (oneEffect == null) {
logger.warn("No effect available at " + textureindex + " for " + matname);
}else {
mat = (sgmat != null) ? (oneEffect.getMaterialDefinition()) :null;
}
} else {
mat = ppfile.findMaterial(matname);
}
// FG-DIFF
// Zu FG abweichende implementierung. Wenn es kein Material gibt, wireframe setzen. Fuer Testen vielleicht ganz gut. Ob auf Dauer auch?
// In FG wird das Material ueber Effect in EffectGeode (teilweise ueber Callback) abgebildet. Effect verbindet direkt zum Shader.
// Darueber wird zumindest wohl die Textur definiert. Hier jetzt das Mesh direkt erzeugen.
eg = new EffectGeode();
// FG-DIFF immer derselbe Name ist doch bloed. Es ist auch nicht erkennbar, dass FG da Logik dran hat. 12.12.17: Tja, jetzt hab ich aber keinen Namen.
//eg.setName("EffectGeode");
eg.setName(po.name);// + ii+"("+i.getNumTriangles()+" tris)");
if (mat != null) {
//12.12.17: im Effect ist das "endgültige" Material enthalten. Der EffectGeode treagt dazu nichts bei, zumindest nichts bekanntes.
//Darum kommt jetzt auch nur noch "echtes" Material rein (wegen preprocess)
eg.material = mat;
//eg.setMaterial(p.mat);
//Effect e<SUF>
//eg.setEffect(e);
foundMaterial.add(matname);
} else {
// 31.12.17 das log ich mal als warning, weils wirklich ein Grund zur Warnung ist
// 18.04.19 das wird dann halt wireframe
logger.warn("no material " + matname + " found");
eg.setMaterial(null);
notFoundMaterial.add(matname);
}
//eg.addDrawable(geometry);
//eg.runGenerators(geometry); // Generate extra data needed by effect
if (group != null) {
group.attach(eg);
}
eg.buildMesh(p/*.geo*/);
}
}
if (group != null) {
return group;
} else {
return eg;
}
}
}
|
125738_3 | /**
* PAINt
*
* Created for the course intro Human-Computer Interaction at the
* Radboud Universiteit Nijmegen
*
* 2013
*/
package nl.PAINt;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.log4j.Logger;
/**
* @author Luuk Scholten & Thom Wiggers
*
*/
public class OptiesPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -8647274997122730322L;
private CanvasPanel canvas;
private JColorChooser colorPicker;
private Logger logger;
private boolean knopjes;
/**
* @param canvas
*
*/
public OptiesPanel(CanvasPanel theCanvas, boolean knopjesenabled) {
logger = Logger.getLogger(getClass());
this.knopjes = knopjesenabled;
canvas = theCanvas;
setPreferredSize(new Dimension(450, canvas.getHeight()));
this.setLayout(new GridLayout(0, 1));
initColorPicker();
if (knopjesenabled) {
this.add(new SliderPanel());
}
this.add(new TimerPanel());
}
private void initColorPicker() {
logger.debug("initialising color picker");
colorPicker = new JColorChooser();
PreviewPanel pp = new PreviewPanel();
colorPicker.getSelectionModel().addChangeListener(pp);
colorPicker.setPreviewPanel(pp);
boolean skipped = false;
for (AbstractColorChooserPanel panel : colorPicker.getChooserPanels()) {
if (!skipped) {
skipped = true;
continue;
} else
colorPicker.removeChooserPanel(panel);
}
this.add(colorPicker);
}
protected class PreviewPanel extends JPanel implements ChangeListener,
ActionListener {
/**
*
*/
private static final long serialVersionUID = 3445719326561602037L;
private JLabel label;
private JPanel block;
private Logger logger;
public PreviewPanel() {
super();
logger = Logger.getLogger(PreviewPanel.class);
this.setLayout(new GridLayout(0, 2));
setPreferredSize(new Dimension(400, 100));
setSize(getPreferredSize());
label = new JLabel("Huidige Kleur: ");
label.setBackground(Color.blue);
label.setSize(getPreferredSize());
label.setVisible(true);
this.block = new JPanel();
block.setSize(80, 80);
block.setBackground(Color.black);
ImageIcon icon = new ImageIcon("resources/kleur_fill.png");
Image img = icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 50, 50, 50,50, null);
ImageIcon newIcon = new ImageIcon(bi);
JButton knopjeFill = new JButton("", newIcon);
knopjeFill.setActionCommand("FILL");
knopjeFill.addActionListener(this);
icon = new ImageIcon("resources/kleur_lijn.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 50, 50, 50,50, null);
newIcon = new ImageIcon(bi);
JButton knopjeLijn = new JButton("", newIcon);
knopjeLijn.setActionCommand("LIJN");
knopjeLijn.addActionListener(this);
add(label);
add(block);
if (knopjes) {
add(knopjeFill);
add(knopjeLijn);
}
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
* )
*/
@Override
public void stateChanged(ChangeEvent e) {
logger.info("Gebruiker koos nieuwe kleur "
+ colorPicker.getColor().toString());
block.setBackground(colorPicker.getColor());
canvas.setActiveColor(colorPicker.getColor());
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent arg0) {
logger.info("Gebruiker klinkte op actie " + arg0.getActionCommand());
switch (arg0.getActionCommand()) {
case "FILL":
canvas.setColor(colorPicker.getColor());
break;
case "LIJN":
canvas.setLineColor(colorPicker.getColor());
break;
default:
IllegalArgumentException e = new IllegalArgumentException("WAT");
logger.error("Unrecognised action in PreviewPanel", e);
throw e;
}
}
}
protected class SliderPanel extends JPanel implements ChangeListener {
/**
*
*/
private static final long serialVersionUID = -6529442891082983907L;
private JSlider lijnDikte;
private Logger logger = Logger.getLogger(SliderPanel.class);
public SliderPanel() {
logger.debug("initialising SliderPanel");
this.setLayout(new GridLayout(0, 2));
this.add(new JLabel("Lijndikte: ", JLabel.RIGHT));
lijnDikte = new JSlider(10, 150, 30);
lijnDikte.addChangeListener(this);
this.add(lijnDikte);
ImageIcon icon = new ImageIcon("resources/layer_up.png");
Image img = icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
ImageIcon newIcon = new ImageIcon(bi);
JButton knopvooruit = new JButton("", newIcon);
knopvooruit.setActionCommand("z-index+");
knopvooruit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("naar voren geklikt");
canvas.moveSelectedBackward();
}
});
icon = new ImageIcon("resources/layer_down.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton knopachteruit = new JButton("", newIcon);
knopachteruit.setActionCommand("z-index-");
knopachteruit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
logger.info("naar achteren geklikt");
canvas.moveSelectedForward();
}
});
icon = new ImageIcon("resources/fill.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton knopFill = new JButton("", newIcon);
knopFill.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("toggledFill geklikt");
canvas.toggleFill();
}
});
icon = new ImageIcon("resources/delete.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton deleteKnopje = new JButton("", newIcon);
deleteKnopje.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("pressed deleteselected");
canvas.deleteSelected();
}
});
if (knopjes) {
this.add(knopvooruit);
this.add(knopachteruit);
this.add(knopFill);
this.add(deleteKnopje);
}
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
* )
*/
@Override
public void stateChanged(ChangeEvent arg0) {
logger.info("Gebruiker koos lijndikte: " + lijnDikte.getValue());
canvas.setLineWidth((float) lijnDikte.getValue() / 10f);
}
}
}
| thomwiggers/Mens-Machine-Interactie | src/nl/PAINt/OptiesPanel.java | 3,532 | /*
* (non-Javadoc)
*
* @see
* javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
* )
*/ | block_comment | nl | /**
* PAINt
*
* Created for the course intro Human-Computer Interaction at the
* Radboud Universiteit Nijmegen
*
* 2013
*/
package nl.PAINt;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.log4j.Logger;
/**
* @author Luuk Scholten & Thom Wiggers
*
*/
public class OptiesPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -8647274997122730322L;
private CanvasPanel canvas;
private JColorChooser colorPicker;
private Logger logger;
private boolean knopjes;
/**
* @param canvas
*
*/
public OptiesPanel(CanvasPanel theCanvas, boolean knopjesenabled) {
logger = Logger.getLogger(getClass());
this.knopjes = knopjesenabled;
canvas = theCanvas;
setPreferredSize(new Dimension(450, canvas.getHeight()));
this.setLayout(new GridLayout(0, 1));
initColorPicker();
if (knopjesenabled) {
this.add(new SliderPanel());
}
this.add(new TimerPanel());
}
private void initColorPicker() {
logger.debug("initialising color picker");
colorPicker = new JColorChooser();
PreviewPanel pp = new PreviewPanel();
colorPicker.getSelectionModel().addChangeListener(pp);
colorPicker.setPreviewPanel(pp);
boolean skipped = false;
for (AbstractColorChooserPanel panel : colorPicker.getChooserPanels()) {
if (!skipped) {
skipped = true;
continue;
} else
colorPicker.removeChooserPanel(panel);
}
this.add(colorPicker);
}
protected class PreviewPanel extends JPanel implements ChangeListener,
ActionListener {
/**
*
*/
private static final long serialVersionUID = 3445719326561602037L;
private JLabel label;
private JPanel block;
private Logger logger;
public PreviewPanel() {
super();
logger = Logger.getLogger(PreviewPanel.class);
this.setLayout(new GridLayout(0, 2));
setPreferredSize(new Dimension(400, 100));
setSize(getPreferredSize());
label = new JLabel("Huidige Kleur: ");
label.setBackground(Color.blue);
label.setSize(getPreferredSize());
label.setVisible(true);
this.block = new JPanel();
block.setSize(80, 80);
block.setBackground(Color.black);
ImageIcon icon = new ImageIcon("resources/kleur_fill.png");
Image img = icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 50, 50, 50,50, null);
ImageIcon newIcon = new ImageIcon(bi);
JButton knopjeFill = new JButton("", newIcon);
knopjeFill.setActionCommand("FILL");
knopjeFill.addActionListener(this);
icon = new ImageIcon("resources/kleur_lijn.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 50, 50, 50,50, null);
newIcon = new ImageIcon(bi);
JButton knopjeLijn = new JButton("", newIcon);
knopjeLijn.setActionCommand("LIJN");
knopjeLijn.addActionListener(this);
add(label);
add(block);
if (knopjes) {
add(knopjeFill);
add(knopjeLijn);
}
}
/*
* (non-Javadoc)
<SUF>*/
@Override
public void stateChanged(ChangeEvent e) {
logger.info("Gebruiker koos nieuwe kleur "
+ colorPicker.getColor().toString());
block.setBackground(colorPicker.getColor());
canvas.setActiveColor(colorPicker.getColor());
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent arg0) {
logger.info("Gebruiker klinkte op actie " + arg0.getActionCommand());
switch (arg0.getActionCommand()) {
case "FILL":
canvas.setColor(colorPicker.getColor());
break;
case "LIJN":
canvas.setLineColor(colorPicker.getColor());
break;
default:
IllegalArgumentException e = new IllegalArgumentException("WAT");
logger.error("Unrecognised action in PreviewPanel", e);
throw e;
}
}
}
protected class SliderPanel extends JPanel implements ChangeListener {
/**
*
*/
private static final long serialVersionUID = -6529442891082983907L;
private JSlider lijnDikte;
private Logger logger = Logger.getLogger(SliderPanel.class);
public SliderPanel() {
logger.debug("initialising SliderPanel");
this.setLayout(new GridLayout(0, 2));
this.add(new JLabel("Lijndikte: ", JLabel.RIGHT));
lijnDikte = new JSlider(10, 150, 30);
lijnDikte.addChangeListener(this);
this.add(lijnDikte);
ImageIcon icon = new ImageIcon("resources/layer_up.png");
Image img = icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
ImageIcon newIcon = new ImageIcon(bi);
JButton knopvooruit = new JButton("", newIcon);
knopvooruit.setActionCommand("z-index+");
knopvooruit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("naar voren geklikt");
canvas.moveSelectedBackward();
}
});
icon = new ImageIcon("resources/layer_down.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton knopachteruit = new JButton("", newIcon);
knopachteruit.setActionCommand("z-index-");
knopachteruit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
logger.info("naar achteren geklikt");
canvas.moveSelectedForward();
}
});
icon = new ImageIcon("resources/fill.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton knopFill = new JButton("", newIcon);
knopFill.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("toggledFill geklikt");
canvas.toggleFill();
}
});
icon = new ImageIcon("resources/delete.png");
img = icon.getImage();
bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = bi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(img, 35, 35, 80,80, null);
newIcon = new ImageIcon(bi);
JButton deleteKnopje = new JButton("", newIcon);
deleteKnopje.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logger.info("pressed deleteselected");
canvas.deleteSelected();
}
});
if (knopjes) {
this.add(knopvooruit);
this.add(knopachteruit);
this.add(knopFill);
this.add(deleteKnopje);
}
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
* )
*/
@Override
public void stateChanged(ChangeEvent arg0) {
logger.info("Gebruiker koos lijndikte: " + lijnDikte.getValue());
canvas.setLineWidth((float) lijnDikte.getValue() / 10f);
}
}
}
|
42839_15 | package Control;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import Exceptions.*;
import Entity.*;
import java.text.DateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class TaskController {
private ArrayList<Task> taskList = new ArrayList<Task>();
private ArrayList<Employee> employeeList = new ArrayList<Employee>();
private ArrayList<Location> locationList = new ArrayList<Location>();
//Adds task to the tasklist
private void addTask(Task task)
{
taskList.add(task);
}
//Adds employee to the employee list
public void addEmployee(Employee employee)
{
employeeList.add(employee);
}
public void addLocation(Location location)
{
locationList.add(location);
}
/*Gets all available employees and put them in an Hashmap for the gui
public HashMap<Integer,String> getAvailableEmployees()
{
HashMap<Integer,String> hmEmployee = new HashMap<Integer,String>();
for(Employee employee: employeeList)
{
hmEmployee.put(employee.getEmployeeNr(), employee.getName());
}
return hmEmployee;
}*/
public ArrayList<Employee> getAvailableEmployees()
{
return employeeList;
}
//Gets all the categories for appointments and adds them to an ArrayList
public Task.Category[] getCategories(){
return Task.Category.values();
}
//Gets all the locations and puts them in an Hashmap for the gui
public HashMap<String, String> getLocations(){
HashMap<String, String> hmLocation = new HashMap<String, String>();
for(Location location: locationList)
{
hmLocation.put(location.getZipcode(), location.getStreetName());
}
return hmLocation;
}
//Create a new task
public Task createTask(int taskId, String notes, boolean approved, boolean signed, String startDateTime, String endDateTime, Task.Category category, ArrayList<Employee> workingEmployeeList, ArrayList<LabTask> labTasks, Patient patient)
{
Task task = null;
try
{
System.out.println("Maken met de dates: " + startDateTime);
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = dateFormat.parse(startDateTime);
Date endDate = dateFormat.parse(endDateTime);
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
if (taskId == -1)
{
task = new Task(notes, approved, signed, startCalendar, endCalendar, category, workingEmployeeList, labTasks, patient);
}
else
{
task = new Task(taskId, notes, approved, signed, startCalendar, endCalendar, category, workingEmployeeList, labTasks, patient);
}
try
{
validateTask(task);
addTask(task);
return task;
}
catch(Exception exp)
{
System.out.println(exp);
}
System.out.println("Start Datum: " + task.getStartDateTime().getTime() + " en eind Datum: " + task.getEndDateTime().getTime());
}
catch(Exception e)
{
System.err.println("One of the dates was not well formatted");
}
return task;
}
public boolean validateTask(Task checkTask) throws SamePatientException, SameEmployeeException
{
boolean valid = true;
//Loop through all the tasks..
for(Task task : taskList)
{
boolean beforeNotAvail = task.getStartDateTime().before(checkTask.getEndDateTime());
boolean afterNotAvail = task.getEndDateTime().after(checkTask.getStartDateTime());
//Check if the Task is beginning or ending into another task
if(beforeNotAvail && afterNotAvail)
{
//If it is the same patient..
if(task.getPatient().equals(checkTask.getPatient()))
{
throw new SamePatientException();
}
//Check on the employees
for(Employee employee : task.getWorkingEmployeeList())
{
if(checkTask.getWorkingEmployeeList().contains(employee))
{
throw new SameEmployeeException();
}
}
}
}
return valid;
}
//Returns the task list
public ArrayList<Task> getTaskList()
{
return taskList;
}
//Search tasks by Patient
public ArrayList<Task> getTasks(Patient patient)
{
ArrayList<Task> foundTasks = new ArrayList<Task>();
for(Task task : taskList)
{
Patient taskPatient = task.getPatient();
if(patient.equals(taskPatient))
{
foundTasks.add(task);
}
}
return foundTasks;
}
//Search tasks by Employee
public ArrayList<Task> getTasks(Employee employee)
{
ArrayList<Task> foundTasks = new ArrayList<Task>();
for(Task task : taskList)
{
ArrayList<Employee> taskEmployees = task.getWorkingEmployeeList();
for(Employee taskEmployee : taskEmployees)
{
if(employee.equals(taskEmployee))
{
foundTasks.add(task);
}
}
}
return foundTasks;
}
//Search tasks by Category
public ArrayList<Task> getTasks(String category)
{
Task.Category searchCategory = categoryStringToEnum(category);
ArrayList<Task> foundTasks = new ArrayList<Task>();
if(searchCategory != null)
{
for(Task task : taskList)
{
Task.Category taskCategory = task.getCategory();
if(searchCategory.equals(taskCategory))
{
foundTasks.add(task);
}
}
}
return foundTasks;
}
private Task.Category categoryStringToEnum(String categoryString)
{
try
{
Task.Category category = Task.Category.valueOf(categoryString.toUpperCase());
return category;
}
catch (IllegalArgumentException exception)
{
System.err.println("Task Category not found: " + categoryString);
return null;
}
}
private Patient getPatientByID(Patient patientID) {
//Auto-generated method stub of zoiets
return null;
}
private Location getLocationByID(Location locationID) {
//Hetzelfde als hierboven
return null;
}
}
| thopstaken/VH12IA | EPD/EPD/src/Control/TaskController.java | 1,885 | //Hetzelfde als hierboven | line_comment | nl | package Control;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import Exceptions.*;
import Entity.*;
import java.text.DateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class TaskController {
private ArrayList<Task> taskList = new ArrayList<Task>();
private ArrayList<Employee> employeeList = new ArrayList<Employee>();
private ArrayList<Location> locationList = new ArrayList<Location>();
//Adds task to the tasklist
private void addTask(Task task)
{
taskList.add(task);
}
//Adds employee to the employee list
public void addEmployee(Employee employee)
{
employeeList.add(employee);
}
public void addLocation(Location location)
{
locationList.add(location);
}
/*Gets all available employees and put them in an Hashmap for the gui
public HashMap<Integer,String> getAvailableEmployees()
{
HashMap<Integer,String> hmEmployee = new HashMap<Integer,String>();
for(Employee employee: employeeList)
{
hmEmployee.put(employee.getEmployeeNr(), employee.getName());
}
return hmEmployee;
}*/
public ArrayList<Employee> getAvailableEmployees()
{
return employeeList;
}
//Gets all the categories for appointments and adds them to an ArrayList
public Task.Category[] getCategories(){
return Task.Category.values();
}
//Gets all the locations and puts them in an Hashmap for the gui
public HashMap<String, String> getLocations(){
HashMap<String, String> hmLocation = new HashMap<String, String>();
for(Location location: locationList)
{
hmLocation.put(location.getZipcode(), location.getStreetName());
}
return hmLocation;
}
//Create a new task
public Task createTask(int taskId, String notes, boolean approved, boolean signed, String startDateTime, String endDateTime, Task.Category category, ArrayList<Employee> workingEmployeeList, ArrayList<LabTask> labTasks, Patient patient)
{
Task task = null;
try
{
System.out.println("Maken met de dates: " + startDateTime);
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = dateFormat.parse(startDateTime);
Date endDate = dateFormat.parse(endDateTime);
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
if (taskId == -1)
{
task = new Task(notes, approved, signed, startCalendar, endCalendar, category, workingEmployeeList, labTasks, patient);
}
else
{
task = new Task(taskId, notes, approved, signed, startCalendar, endCalendar, category, workingEmployeeList, labTasks, patient);
}
try
{
validateTask(task);
addTask(task);
return task;
}
catch(Exception exp)
{
System.out.println(exp);
}
System.out.println("Start Datum: " + task.getStartDateTime().getTime() + " en eind Datum: " + task.getEndDateTime().getTime());
}
catch(Exception e)
{
System.err.println("One of the dates was not well formatted");
}
return task;
}
public boolean validateTask(Task checkTask) throws SamePatientException, SameEmployeeException
{
boolean valid = true;
//Loop through all the tasks..
for(Task task : taskList)
{
boolean beforeNotAvail = task.getStartDateTime().before(checkTask.getEndDateTime());
boolean afterNotAvail = task.getEndDateTime().after(checkTask.getStartDateTime());
//Check if the Task is beginning or ending into another task
if(beforeNotAvail && afterNotAvail)
{
//If it is the same patient..
if(task.getPatient().equals(checkTask.getPatient()))
{
throw new SamePatientException();
}
//Check on the employees
for(Employee employee : task.getWorkingEmployeeList())
{
if(checkTask.getWorkingEmployeeList().contains(employee))
{
throw new SameEmployeeException();
}
}
}
}
return valid;
}
//Returns the task list
public ArrayList<Task> getTaskList()
{
return taskList;
}
//Search tasks by Patient
public ArrayList<Task> getTasks(Patient patient)
{
ArrayList<Task> foundTasks = new ArrayList<Task>();
for(Task task : taskList)
{
Patient taskPatient = task.getPatient();
if(patient.equals(taskPatient))
{
foundTasks.add(task);
}
}
return foundTasks;
}
//Search tasks by Employee
public ArrayList<Task> getTasks(Employee employee)
{
ArrayList<Task> foundTasks = new ArrayList<Task>();
for(Task task : taskList)
{
ArrayList<Employee> taskEmployees = task.getWorkingEmployeeList();
for(Employee taskEmployee : taskEmployees)
{
if(employee.equals(taskEmployee))
{
foundTasks.add(task);
}
}
}
return foundTasks;
}
//Search tasks by Category
public ArrayList<Task> getTasks(String category)
{
Task.Category searchCategory = categoryStringToEnum(category);
ArrayList<Task> foundTasks = new ArrayList<Task>();
if(searchCategory != null)
{
for(Task task : taskList)
{
Task.Category taskCategory = task.getCategory();
if(searchCategory.equals(taskCategory))
{
foundTasks.add(task);
}
}
}
return foundTasks;
}
private Task.Category categoryStringToEnum(String categoryString)
{
try
{
Task.Category category = Task.Category.valueOf(categoryString.toUpperCase());
return category;
}
catch (IllegalArgumentException exception)
{
System.err.println("Task Category not found: " + categoryString);
return null;
}
}
private Patient getPatientByID(Patient patientID) {
//Auto-generated method stub of zoiets
return null;
}
private Location getLocationByID(Location locationID) {
//Hetzelfde als<SUF>
return null;
}
}
|