answer
stringlengths 17
10.2M
|
|---|
package vsb.fou.batch.spring.poc.importpersons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemReader;
import org.springframework.stereotype.Component;
import vsb.fou.batch.spring.poc.util.TimeStamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Component
@StepScope
public class PersonReader implements ItemReader<Person>, StepExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonReader.class);
private final String createdDate = TimeStamp.getTstamp();
private final List<Person> persons;
private AtomicInteger index = new AtomicInteger(0);
public PersonReader() {
persons = new ArrayList<>();
persons.add(new Person("Vegard", "Bye"));
persons.add(new Person("Sally", "Saadi"));
}
@Override
public Person read() {
if (index.get() >= persons.size()) {
index.set(0);
return null;
}
Person person = persons.get(index.getAndAdd(1));
LOGGER.info(createdDate + " Leste: " + person);
return person;
}
@Override
public void beforeStep(StepExecution stepExecution) {
JobParameters jobParameters = stepExecution.getJobParameters();
LOGGER.info("
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
JobParameters jobParameters = stepExecution.getJobParameters();
LOGGER.info("
return ExitStatus.COMPLETED;
}
}
|
package com.sdl.dxa.modules;
import com.sdl.dxa.modules.model.TSI1757.Tsi1757TestEntity1;
import com.sdl.dxa.modules.model.TSI1757.Tsi1757TestEntity2;
import com.sdl.dxa.modules.model.TSI1757.Tsi1757TestEntity3;
import com.sdl.dxa.modules.model.TSI1758.Tsi1758TestEmbedded2Entity;
import com.sdl.dxa.modules.model.TSI1758.Tsi1758TestEmbeddedEntity;
import com.sdl.dxa.modules.model.TSI1758.Tsi1758TestEntity;
import com.sdl.dxa.modules.model.TSI1856.Tsi1856TestEntity;
import com.sdl.dxa.modules.model.TSI1946.Tsi1946TestEntity;
import com.sdl.dxa.modules.model.TSI2315.CompLinkTest;
import com.sdl.dxa.modules.model.TSI2315.TestEntity;
import com.sdl.dxa.modules.model.TSI2316.Tsi2316TestEntity;
import com.sdl.dxa.modules.model.TSI2316.Tsi2316TestKeyword;
import com.sdl.dxa.modules.model.TSI811.Tsi811PageModel;
import com.sdl.dxa.modules.model.TSI811.Tsi811TestEntity;
import com.sdl.dxa.modules.model.TSI811.Tsi811TestKeyword;
import com.sdl.dxa.modules.model.ecl.EclTest;
import com.sdl.dxa.modules.model.embed.EmbedChild;
import com.sdl.dxa.modules.model.embed.EmbedParent;
import com.sdl.webapp.common.api.mapping.views.AbstractInitializer;
import com.sdl.webapp.common.api.mapping.views.RegisteredViewModel;
import com.sdl.webapp.common.api.mapping.views.RegisteredViewModels;
import com.sdl.webapp.common.api.model.page.DefaultPageModel;
import org.springframework.stereotype.Component;
@Component
@RegisteredViewModels({
@RegisteredViewModel(viewName = "EmbedParent", modelClass = EmbedParent.class),
@RegisteredViewModel(modelClass = EmbedChild.class),
@RegisteredViewModel(viewName = "TestFlickrImage", modelClass = EclTest.class),
@RegisteredViewModel(viewName = "TSI1758Test", modelClass = Tsi1758TestEntity.class),
@RegisteredViewModel(viewName = "TSI1758TestEmbedded", modelClass = Tsi1758TestEmbeddedEntity.class),
@RegisteredViewModel(viewName = "TSI1758TestEmbedded2", modelClass = Tsi1758TestEmbedded2Entity.class),
@RegisteredViewModel(viewName = "SimpleTestPage", modelClass = DefaultPageModel.class),
@RegisteredViewModel(viewName = "TSI811TestPage", modelClass = Tsi811PageModel.class),
@RegisteredViewModel(viewName = "TSI811Test", modelClass = Tsi811TestEntity.class),
@RegisteredViewModel(modelClass = Tsi811TestKeyword.class),
@RegisteredViewModel(viewName = "TSI1946Test", modelClass = Tsi1946TestEntity.class),
@RegisteredViewModel(viewName = "TSI1947Test", modelClass = TestEntity.class),
@RegisteredViewModel(viewName = "TSI1757Test3", modelClass = Tsi1757TestEntity3.class),
@RegisteredViewModel(modelClass = Tsi1757TestEntity1.class),
@RegisteredViewModel(modelClass = Tsi1757TestEntity2.class),
@RegisteredViewModel(viewName = "TSI1856Test", modelClass = Tsi1856TestEntity.class),
@RegisteredViewModel(viewName = "TSI2316Test", modelClass = Tsi2316TestEntity.class),
@RegisteredViewModel(modelClass = Tsi2316TestKeyword.class),
@RegisteredViewModel(viewName = "CompLinkTest", modelClass = CompLinkTest.class),
@RegisteredViewModel(modelClass = TestEntity.class)
})
public class TestModuleInitializer extends AbstractInitializer {
@Override
protected String getAreaName() {
return "Test";
}
}
|
package org.knowm.xchange.coinbasepro;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.knowm.xchange.coinbasepro.dto.CoinbaseProTransfer;
import org.knowm.xchange.coinbasepro.dto.account.CoinbaseProAccount;
import org.knowm.xchange.coinbasepro.dto.marketdata.*;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProFill;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProOrder;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProOrderFlags;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProPlaceLimitOrder;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProPlaceMarketOrder;
import org.knowm.xchange.coinbasepro.dto.trade.CoinbaseProPlaceOrder;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.Order.OrderStatus;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.FundingRecord;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.CurrencyPairMetaData;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.StopOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoinbaseProAdapters {
private static Logger logger = LoggerFactory.getLogger(CoinbaseProAdapters.class);
private CoinbaseProAdapters() {}
protected static Date parseDate(final String rawDate) {
String modified;
if (rawDate.length() > 23) {
modified = rawDate.substring(0, 23);
} else if (rawDate.endsWith("Z")) {
switch (rawDate.length()) {
case 20:
modified = rawDate.substring(0, 19) + ".000";
break;
case 22:
modified = rawDate.substring(0, 21) + "00";
break;
case 23:
modified = rawDate.substring(0, 22) + "0";
break;
default:
modified = rawDate;
break;
}
} else {
switch (rawDate.length()) {
case 19:
modified = rawDate + ".000";
break;
case 21:
modified = rawDate + "00";
break;
case 22:
modified = rawDate + "0";
break;
default:
modified = rawDate;
break;
}
}
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.parse(modified);
} catch (ParseException e) {
logger.warn("unable to parse rawDate={} modified={}", rawDate, modified, e);
return null;
}
}
public static Ticker adaptTicker(
CoinbaseProProductTicker ticker, CoinbaseProProductStats stats, CurrencyPair currencyPair) {
BigDecimal last = ticker.getPrice();
BigDecimal open = stats.getOpen();
BigDecimal high = stats.getHigh();
BigDecimal low = stats.getLow();
BigDecimal buy = ticker.getBid();
BigDecimal sell = ticker.getAsk();
BigDecimal volume = ticker.getVolume();
Date date = parseDate(ticker.getTime());
return new Ticker.Builder()
.currencyPair(currencyPair)
.last(last)
.open(open)
.high(high)
.low(low)
.bid(buy)
.ask(sell)
.volume(volume)
.timestamp(date)
.build();
}
public static OrderBook adaptOrderBook(
CoinbaseProProductBook book, CurrencyPair currencyPair, Date date) {
List<LimitOrder> asks = toLimitOrderList(book.getAsks(), OrderType.ASK, currencyPair);
List<LimitOrder> bids = toLimitOrderList(book.getBids(), OrderType.BID, currencyPair);
return new OrderBook(date, asks, bids);
}
public static OrderBook adaptOrderBook(CoinbaseProProductBook book, CurrencyPair currencyPair) {
return adaptOrderBook(book, currencyPair, null);
}
private static List<LimitOrder> toLimitOrderList(
CoinbaseProProductBookEntry[] levels, OrderType orderType, CurrencyPair currencyPair) {
List<LimitOrder> allLevels = new ArrayList<>();
if (levels != null) {
for (int i = 0; i < levels.length; i++) {
CoinbaseProProductBookEntry ask = levels[i];
allLevels.add(
new LimitOrder(orderType, ask.getVolume(), currencyPair, "0", null, ask.getPrice()));
}
}
return allLevels;
}
public static Wallet adaptAccountInfo(CoinbaseProAccount[] coinbaseProAccounts) {
List<Balance> balances = new ArrayList<>(coinbaseProAccounts.length);
for (int i = 0; i < coinbaseProAccounts.length; i++) {
CoinbaseProAccount coinbaseProAccount = coinbaseProAccounts[i];
balances.add(
new Balance(
Currency.getInstance(coinbaseProAccount.getCurrency()),
coinbaseProAccount.getBalance(),
coinbaseProAccount.getAvailable(),
coinbaseProAccount.getHold()));
}
return new Wallet(coinbaseProAccounts[0].getProfile_id(), balances);
}
@SuppressWarnings("unchecked")
public static OpenOrders adaptOpenOrders(CoinbaseProOrder[] coinbaseExOpenOrders) {
Stream<Order> orders =
Arrays.asList(coinbaseExOpenOrders).stream().map(CoinbaseProAdapters::adaptOrder);
Map<Boolean, List<Order>> twoTypes =
orders.collect(Collectors.partitioningBy(t -> t instanceof LimitOrder));
@SuppressWarnings("rawtypes")
List limitOrders = twoTypes.get(true);
return new OpenOrders(limitOrders, twoTypes.get(false));
}
public static Order adaptOrder(CoinbaseProOrder order) {
OrderType type = order.getSide().equals("buy") ? OrderType.BID : OrderType.ASK;
CurrencyPair currencyPair = new CurrencyPair(order.getProductId().replace('-', '/'));
Date createdAt = parseDate(order.getCreatedAt());
OrderStatus orderStatus = adaptOrderStatus(order);
final BigDecimal averagePrice;
if (order.getFilledSize().signum() == 0) {
averagePrice = BigDecimal.ZERO;
} else {
averagePrice = order.getExecutedvalue().divide(order.getFilledSize(), new MathContext(8));
}
if (order.getType().equals("market")) {
return new MarketOrder(
type,
order.getSize(),
currencyPair,
order.getId(),
createdAt,
averagePrice,
order.getFilledSize(),
order.getFillFees(),
orderStatus);
} else if (order.getType().equals("limit")) {
if (order.getStop() == null) {
return new LimitOrder(
type,
order.getSize(),
currencyPair,
order.getId(),
createdAt,
order.getPrice(),
averagePrice,
order.getFilledSize(),
order.getFillFees(),
orderStatus);
} else {
return new StopOrder(
type,
order.getSize(),
currencyPair,
order.getId(),
createdAt,
order.getStopPrice(),
averagePrice,
order.getFilledSize(),
orderStatus);
}
}
return null;
}
public static OrderStatus[] adaptOrderStatuses(CoinbaseProOrder[] orders) {
OrderStatus[] orderStatuses = new OrderStatus[orders.length];
Integer i = 0;
for (CoinbaseProOrder coinbaseProOrder : orders) {
orderStatuses[i++] = adaptOrderStatus(coinbaseProOrder);
}
return orderStatuses;
}
/** The status from the CoinbaseProOrder object converted to xchange status */
public static OrderStatus adaptOrderStatus(CoinbaseProOrder order) {
if (order.getStatus().equals("pending")) {
return OrderStatus.PENDING_NEW;
}
if (order.getStatus().equals("done") || order.getStatus().equals("settled")) {
if (order.getDoneReason().equals("filled")) {
return OrderStatus.FILLED;
}
if (order.getDoneReason().equals("canceled")) {
return OrderStatus.CANCELED;
}
return OrderStatus.UNKNOWN;
}
if (order.getFilledSize().signum() == 0) {
if (order.getStatus().equals("open") && order.getStop() != null) {
// This is a massive edge case of a stop triggering but not immediately
// fulfilling. STOPPED status is only currently used by the HitBTC and
// YoBit implementations and in both cases it looks like a
// misunderstanding and those should return CANCELLED. Should we just
// remove this status?
return OrderStatus.STOPPED;
}
return OrderStatus.NEW;
}
if (order.getFilledSize().compareTo(BigDecimal.ZERO) > 0
// if size >= filledSize order should be partially filled
&& order.getSize().compareTo(order.getFilledSize()) >= 0)
return OrderStatus.PARTIALLY_FILLED;
return OrderStatus.UNKNOWN;
}
public static Trades adaptTrades(
List<CoinbaseProTrade> gdaxTradesList, CurrencyPair currencyPair) {
CoinbaseProTrade[] tradeArray = new CoinbaseProTrade[gdaxTradesList.size()];
gdaxTradesList.toArray(tradeArray);
return CoinbaseProAdapters.adaptTrades(tradeArray, currencyPair);
}
public static UserTrades adaptTradeHistory(CoinbaseProFill[] coinbaseExFills) {
List<UserTrade> trades = new ArrayList<>(coinbaseExFills.length);
for (int i = 0; i < coinbaseExFills.length; i++) {
CoinbaseProFill fill = coinbaseExFills[i];
OrderType type = fill.getSide().equals("buy") ? OrderType.BID : OrderType.ASK;
CurrencyPair currencyPair = new CurrencyPair(fill.getProductId().replace('-', '/'));
UserTrade t =
new UserTrade(
type,
fill.getSize(),
currencyPair,
fill.getPrice(),
parseDate(fill.getCreatedAt()),
String.valueOf(fill.getTradeId()),
fill.getOrderId(),
fill.getFee(),
currencyPair.counter);
trades.add(t);
}
return new UserTrades(trades, TradeSortType.SortByID);
}
public static Trades adaptTrades(CoinbaseProTrade[] coinbaseExTrades, CurrencyPair currencyPair) {
List<Trade> trades = new ArrayList<>(coinbaseExTrades.length);
for (int i = 0; i < coinbaseExTrades.length; i++) {
CoinbaseProTrade trade = coinbaseExTrades[i];
// yes, sell means buy for coinbasePro reported trades..
OrderType type = trade.getSide().equals("sell") ? OrderType.BID : OrderType.ASK;
Trade t =
new Trade(
type,
trade.getSize(),
currencyPair,
trade.getPrice(),
parseDate(trade.getTimestamp()),
String.valueOf(trade.getTradeId()));
t.setMakerOrderId(trade.getMakerOrderId());
t.setTakerOrderId(trade.getTakerOrderId());
trades.add(t);
}
return new Trades(trades, coinbaseExTrades[0].getTradeId(), TradeSortType.SortByID);
}
public static CurrencyPair adaptCurrencyPair(CoinbaseProProduct product) {
return new CurrencyPair(product.getBaseCurrency(), product.getTargetCurrency());
}
private static Currency adaptCurrency(CoinbaseProCurrency currency) {
return new Currency(currency.getId());
}
private static int numberOfDecimals(BigDecimal value) {
double d = value.doubleValue();
return -(int) Math.round(Math.log10(d));
}
public static ExchangeMetaData adaptToExchangeMetaData(
ExchangeMetaData exchangeMetaData,
CoinbaseProProduct[] products,
CoinbaseProCurrency[] cbCurrencies) {
Map<CurrencyPair, CurrencyPairMetaData> currencyPairs = exchangeMetaData.getCurrencyPairs();
Map<Currency, CurrencyMetaData> currencies = exchangeMetaData.getCurrencies();
for (CoinbaseProProduct product : products) {
BigDecimal minSize = product.getBaseMinSize();
BigDecimal maxSize = product.getBaseMaxSize();
CurrencyPair pair = adaptCurrencyPair(product);
CurrencyPairMetaData staticMetaData = exchangeMetaData.getCurrencyPairs().get(pair);
int baseScale = numberOfDecimals(product.getBaseIncrement());
int priceScale = numberOfDecimals(product.getQuoteIncrement());
CurrencyPairMetaData cpmd =
new CurrencyPairMetaData(
new BigDecimal("0.25"), // Trading fee at Coinbase is 0.25 %
minSize,
maxSize,
baseScale,
priceScale,
staticMetaData != null ? staticMetaData.getFeeTiers() : null,
null,
pair.counter);
currencyPairs.put(pair, cpmd);
}
for (CoinbaseProCurrency currency : cbCurrencies) {
Currency cur = adaptCurrency(currency);
int scale = numberOfDecimals(currency.getMaxPrecision());
// Coinbase has a 0 withdrawal fee
currencies.put(cur, new CurrencyMetaData(scale, BigDecimal.ZERO));
}
return new ExchangeMetaData(
currencyPairs,
currencies,
exchangeMetaData.getPublicRateLimits(),
exchangeMetaData.getPrivateRateLimits(),
true);
}
public static String adaptProductID(CurrencyPair currencyPair) {
return currencyPair.base.getCurrencyCode() + "-" + currencyPair.counter.getCurrencyCode();
}
public static CoinbaseProPlaceOrder.Side adaptSide(OrderType orderType) {
return orderType == OrderType.ASK
? CoinbaseProPlaceOrder.Side.sell
: CoinbaseProPlaceOrder.Side.buy;
}
public static CoinbaseProPlaceOrder.Stop adaptStop(OrderType orderType) {
return orderType == OrderType.ASK
? CoinbaseProPlaceOrder.Stop.loss
: CoinbaseProPlaceOrder.Stop.entry;
}
public static CoinbaseProPlaceLimitOrder adaptCoinbaseProPlaceLimitOrder(LimitOrder limitOrder) {
CoinbaseProPlaceLimitOrder.Builder builder =
new CoinbaseProPlaceLimitOrder.Builder()
.price(limitOrder.getLimitPrice())
.type(CoinbaseProPlaceOrder.Type.limit)
.productId(adaptProductID(limitOrder.getCurrencyPair()))
.side(adaptSide(limitOrder.getType()))
.size(limitOrder.getOriginalAmount());
if (limitOrder.getOrderFlags().contains(CoinbaseProOrderFlags.POST_ONLY))
builder.postOnly(true);
if (limitOrder.getOrderFlags().contains(CoinbaseProOrderFlags.FILL_OR_KILL))
builder.timeInForce(CoinbaseProPlaceLimitOrder.TimeInForce.FOK);
if (limitOrder.getOrderFlags().contains(CoinbaseProOrderFlags.IMMEDIATE_OR_CANCEL))
builder.timeInForce(CoinbaseProPlaceLimitOrder.TimeInForce.IOC);
return builder.build();
}
public static CoinbaseProPlaceMarketOrder adaptCoinbaseProPlaceMarketOrder(
MarketOrder marketOrder) {
return new CoinbaseProPlaceMarketOrder.Builder()
.productId(adaptProductID(marketOrder.getCurrencyPair()))
.type(CoinbaseProPlaceOrder.Type.market)
.side(adaptSide(marketOrder.getType()))
.size(marketOrder.getOriginalAmount())
.build();
}
/**
* Creates a 'stop' order. Stop limit order converts to a limit order when the stop amount is
* triggered. The limit order can have a different price than the stop price.
*
* <p>If the stop order has no limit price it will execute as a market order once the stop price
* is broken
*
* @param stopOrder
* @return
*/
public static CoinbaseProPlaceOrder adaptCoinbaseProStopOrder(StopOrder stopOrder) {
// stop orders can also execute as 'stop limit' orders, that is converting to
// a limit order, but a traditional 'stop' order converts to a market order
if (stopOrder.getLimitPrice() == null) {
return new CoinbaseProPlaceMarketOrder.Builder()
.productId(adaptProductID(stopOrder.getCurrencyPair()))
.type(CoinbaseProPlaceOrder.Type.market)
.side(adaptSide(stopOrder.getType()))
.size(stopOrder.getOriginalAmount())
.stop(adaptStop(stopOrder.getType()))
.stopPrice(stopOrder.getStopPrice())
.build();
}
return new CoinbaseProPlaceLimitOrder.Builder()
.productId(adaptProductID(stopOrder.getCurrencyPair()))
.type(CoinbaseProPlaceOrder.Type.limit)
.side(adaptSide(stopOrder.getType()))
.size(stopOrder.getOriginalAmount())
.stop(adaptStop(stopOrder.getType()))
.stopPrice(stopOrder.getStopPrice())
.price(stopOrder.getLimitPrice())
.build();
}
public static FundingRecord adaptFundingRecord(
Currency currency, CoinbaseProTransfer coinbaseProTransfer) {
FundingRecord.Status status = FundingRecord.Status.PROCESSING;
Date processedAt = coinbaseProTransfer.processedAt();
Date canceledAt = coinbaseProTransfer.canceledAt();
if (canceledAt != null) status = FundingRecord.Status.CANCELLED;
else if (processedAt != null) status = FundingRecord.Status.COMPLETE;
Date timestamp = coinbaseProTransfer.createdAt();
String address = coinbaseProTransfer.getDetails().getCryptoAddress();
if (address == null) address = coinbaseProTransfer.getDetails().getSentToAddress();
return new FundingRecord(
address,
timestamp,
currency,
coinbaseProTransfer.amount(),
coinbaseProTransfer.getId(),
coinbaseProTransfer.getDetails().getCryptoTransactionHash(),
coinbaseProTransfer.type(),
status,
null,
null,
null);
}
}
|
package org.knowm.xchange.kraken.service;
import java.io.IOException;
import java.util.Map;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.kraken.KrakenUtils;
import org.knowm.xchange.kraken.dto.account.KrakenTradeVolume;
import org.knowm.xchange.kraken.dto.account.results.KrakenTradeVolumeResult;
import org.knowm.xchange.kraken.dto.trade.KrakenOpenPosition;
import org.knowm.xchange.kraken.dto.trade.KrakenOrder;
import org.knowm.xchange.kraken.dto.trade.KrakenOrderResponse;
import org.knowm.xchange.kraken.dto.trade.KrakenStandardOrder;
import org.knowm.xchange.kraken.dto.trade.KrakenStandardOrder.KrakenOrderBuilder;
import org.knowm.xchange.kraken.dto.trade.KrakenTrade;
import org.knowm.xchange.kraken.dto.trade.KrakenType;
import org.knowm.xchange.kraken.dto.trade.results.KrakenCancelOrderResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenCancelOrderResult.KrakenCancelOrderResponse;
import org.knowm.xchange.kraken.dto.trade.results.KrakenClosedOrdersResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenOpenOrdersResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenOpenPositionsResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenOrderResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenQueryOrderResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenQueryTradeResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenTradeHistoryResult;
import org.knowm.xchange.kraken.dto.trade.results.KrakenTradeHistoryResult.KrakenTradeHistory;
public class KrakenTradeServiceRaw extends KrakenBaseService {
/**
* Constructor
*
* @param exchange
*/
public KrakenTradeServiceRaw(Exchange exchange) {
super(exchange);
}
public Map<String, KrakenOrder> getKrakenOpenOrders() throws IOException {
return getKrakenOpenOrders(false, null);
}
public Map<String, KrakenOrder> getKrakenOpenOrders(boolean includeTrades, String userRef)
throws IOException {
KrakenOpenOrdersResult result =
kraken.openOrders(
includeTrades,
userRef,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result).getOrders();
}
public Map<String, KrakenOrder> getKrakenClosedOrders() throws IOException {
return getKrakenClosedOrders(false, null, null, null, null, null);
}
public Map<String, KrakenOrder> getKrakenClosedOrders(
boolean includeTrades,
String userRef,
String start,
String end,
String offset,
String closeTime)
throws IOException {
KrakenClosedOrdersResult result =
kraken.closedOrders(
includeTrades,
userRef,
start,
end,
offset,
closeTime,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result).getOrders();
}
public Map<String, KrakenOrder> queryKrakenOrders(String... transactionIds) throws IOException {
return queryKrakenOrders(false, null, transactionIds);
}
public KrakenQueryOrderResult queryKrakenOrdersResult(
boolean includeTrades, String userRef, String... transactionIds) throws IOException {
KrakenQueryOrderResult krakenQueryOrderResult =
kraken.queryOrders(
includeTrades,
userRef,
createDelimitedString(transactionIds),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return krakenQueryOrderResult;
}
public Map<String, KrakenOrder> queryKrakenOrders(
boolean includeTrades, String userRef, String... transactionIds) throws IOException {
KrakenQueryOrderResult result =
kraken.queryOrders(
includeTrades,
userRef,
createDelimitedString(transactionIds),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result);
}
public KrakenTradeHistory getKrakenTradeHistory() throws IOException {
return getKrakenTradeHistory(null, false, null, null, null);
}
public KrakenTradeHistory getKrakenTradeHistory(
String type, boolean includeTrades, Long start, Long end, Long offset) throws IOException {
KrakenTradeHistoryResult result =
kraken.tradeHistory(
type,
includeTrades,
start,
end,
offset,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result);
}
public Map<String, KrakenTrade> queryKrakenTrades(String... transactionIds) throws IOException {
return queryKrakenTrades(false, transactionIds);
}
public Map<String, KrakenTrade> queryKrakenTrades(boolean includeTrades, String... transactionIds)
throws IOException {
KrakenQueryTradeResult result =
kraken.queryTrades(
includeTrades,
createDelimitedString(transactionIds),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result);
}
public Map<String, KrakenOpenPosition> getOpenPositions() throws IOException {
return getOpenPositions(false);
}
public Map<String, KrakenOpenPosition> getOpenPositions(boolean doCalcs, String... transactionIds)
throws IOException {
KrakenOpenPositionsResult result =
kraken.openPositions(
createDelimitedString(transactionIds),
doCalcs,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result);
}
public KrakenOrderResponse placeKrakenMarketOrder(MarketOrder marketOrder) throws IOException {
KrakenType type = KrakenType.fromOrderType(marketOrder.getType());
KrakenOrderBuilder orderBuilder =
KrakenStandardOrder.getMarketOrderBuilder(
marketOrder.getCurrencyPair(), type, marketOrder.getOriginalAmount())
.withOrderFlags(marketOrder.getOrderFlags())
.withLeverage( marketOrder.getLeverage() );
return placeKrakenOrder(orderBuilder.buildOrder());
}
public KrakenOrderResponse placeKrakenLimitOrder(LimitOrder limitOrder) throws IOException {
KrakenType type = KrakenType.fromOrderType(limitOrder.getType());
KrakenOrderBuilder krakenOrderBuilder =
KrakenStandardOrder.getLimitOrderBuilder(
limitOrder.getCurrencyPair(),
type,
limitOrder.getLimitPrice().toPlainString(),
limitOrder.getOriginalAmount())
.withOrderFlags(limitOrder.getOrderFlags())
.withLeverage( limitOrder.getLeverage() );
return placeKrakenOrder(krakenOrderBuilder.buildOrder());
}
public KrakenOrderResponse placeKrakenOrder(KrakenStandardOrder krakenStandardOrder)
throws IOException {
KrakenOrderResult result = null;
if (!krakenStandardOrder.isValidateOnly()) {
result =
kraken.addOrder(
KrakenUtils.createKrakenCurrencyPair(krakenStandardOrder.getAssetPair()),
krakenStandardOrder.getType().toString(),
krakenStandardOrder.getOrderType().toApiFormat(),
krakenStandardOrder.getPrice(),
krakenStandardOrder.getSecondaryPrice(),
krakenStandardOrder.getVolume().toPlainString(),
krakenStandardOrder.getLeverage(),
krakenStandardOrder.getPositionTxId(),
delimitSet(krakenStandardOrder.getOrderFlags()),
krakenStandardOrder.getStartTime(),
krakenStandardOrder.getExpireTime(),
krakenStandardOrder.getUserRefId(),
krakenStandardOrder.getCloseOrder(),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
} else {
result =
kraken.addOrderValidateOnly(
KrakenUtils.createKrakenCurrencyPair(krakenStandardOrder.getAssetPair()),
krakenStandardOrder.getType().toString(),
krakenStandardOrder.getOrderType().toApiFormat(),
krakenStandardOrder.getPrice(),
krakenStandardOrder.getSecondaryPrice(),
krakenStandardOrder.getVolume().toPlainString(),
krakenStandardOrder.getLeverage(),
krakenStandardOrder.getPositionTxId(),
delimitSet(krakenStandardOrder.getOrderFlags()),
krakenStandardOrder.getStartTime(),
krakenStandardOrder.getExpireTime(),
krakenStandardOrder.getUserRefId(),
true,
krakenStandardOrder.getCloseOrder(),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
}
return checkResult(result);
}
public KrakenCancelOrderResponse cancelKrakenOrder(String orderId) throws IOException {
KrakenCancelOrderResult result =
kraken.cancelOrder(
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory(),
orderId);
return checkResult(result);
}
protected KrakenTradeVolume getTradeVolume(CurrencyPair... currencyPairs) throws IOException {
KrakenTradeVolumeResult result =
kraken.tradeVolume(
delimitAssetPairs(currencyPairs),
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(result);
}
public Map<String, KrakenOrder> getOrders(String... orderIds) throws IOException {
String orderIdsString = String.join(",", orderIds);
KrakenQueryOrderResult krakenOrderResult =
kraken.queryOrders(
false,
null,
orderIdsString,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return checkResult(krakenOrderResult);
}
}
|
package org.knowm.xchange.therock.service;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.*;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair;
import org.knowm.xchange.service.trade.params.CancelOrderByIdParams;
import org.knowm.xchange.service.trade.params.CancelOrderParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsIdSpan;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
import org.knowm.xchange.therock.TheRockAdapters;
import org.knowm.xchange.therock.TheRockExchange;
import org.knowm.xchange.therock.dto.TheRockException;
import org.knowm.xchange.therock.dto.trade.TheRockOrder;
/**
* @author Matija Mazi
* @author Pnk
*/
public class TheRockTradeService extends TheRockTradeServiceRaw implements TradeService {
public TheRockTradeService(Exchange exchange) {
super(exchange);
}
@Override
public String placeMarketOrder(MarketOrder order) throws IOException, ExchangeException {
final TheRockOrder placedOrder = placeTheRockOrder(order.getCurrencyPair(), order.getOriginalAmount(), null,
TheRockAdapters.adaptSide(order.getType()), TheRockOrder.Type.market);
return placedOrder.getId().toString();
}
@Override
public String placeLimitOrder(LimitOrder order) throws IOException, ExchangeException {
final TheRockOrder placedOrder = placeTheRockOrder(order.getCurrencyPair(), order.getOriginalAmount(), order.getLimitPrice(),
TheRockAdapters.adaptSide(order.getType()), TheRockOrder.Type.limit);
return placedOrder.getId().toString();
}
@Override
public String placeStopOrder(StopOrder stopOrder) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Not available from exchange since TheRock needs currency pair in order to return open orders
*/
@Override
public OpenOrders getOpenOrders() throws IOException {
return getOpenOrders(createOpenOrdersParams());
}
@Override
public OpenOrders getOpenOrders(
OpenOrdersParams params) throws IOException {
CurrencyPair currencyPair = null;
if (params instanceof OpenOrdersParamCurrencyPair) {
currencyPair = ((OpenOrdersParamCurrencyPair) params).getCurrencyPair();
}
if (currencyPair == null) {
throw new ExchangeException("CurrencyPair parameter must not be null.");
}
return TheRockAdapters.adaptOrders(getTheRockOrders(currencyPair));
}
/**
* Not available from exchange since TheRock needs currency pair in order to cancel an order
*/
@Override
public boolean cancelOrder(String orderId) throws IOException {
CurrencyPair cp = (CurrencyPair) exchange.getExchangeSpecification().getExchangeSpecificParameters().get(TheRockExchange.CURRENCY_PAIR);
if (cp == null) {
throw new ExchangeException("Provide TheRockCancelOrderParams with orderId and currencyPair");
}
return cancelOrder(cp, orderId);
}
@Override
public boolean cancelOrder(
CancelOrderParams params) throws IOException {
if (!(params instanceof CancelOrderByIdParams)) {
return false;
}
CancelOrderByIdParams paramId = (CancelOrderByIdParams) params;
CurrencyPair currencyPair;
if (params instanceof CancelOrderByCurrencyPair) {
CancelOrderByCurrencyPair paramCurrencyPair = (CancelOrderByCurrencyPair) params;
currencyPair = paramCurrencyPair.getCurrencyPair();
} else {
currencyPair = null;
}
return cancelOrder(currencyPair, paramId.getOrderId());
}
private boolean cancelOrder(CurrencyPair currencyPair, String orderId) throws TheRockException, NumberFormatException, IOException {
TheRockOrder cancelledOrder = cancelTheRockOrder(currencyPair, Long.parseLong(orderId));
return "deleted".equals(cancelledOrder.getStatus());
}
/**
* Not available from exchange since TheRock needs currency pair in order to return/show the order
*/
@Override
public Collection<Order> getOrder(
String... orderIds) throws IOException {
throw new NotAvailableFromExchangeException();
}
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
if (!(params instanceof TradeHistoryParamCurrencyPair)) {
throw new ExchangeException("TheRock API recquires " + TradeHistoryParamCurrencyPair.class.getName());
}
TradeHistoryParamCurrencyPair pairParams = (TradeHistoryParamCurrencyPair) params;
Long sinceTradeId = null; // get all trades starting from a specific trade_id
if (params instanceof TradeHistoryParamsIdSpan) {
TradeHistoryParamsIdSpan trId = (TradeHistoryParamsIdSpan) params;
try {
sinceTradeId = Long.valueOf(trId.getStartId());
} catch (Throwable ignored) {
}
}
Date after = null;
Date before = null;
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan time = (TradeHistoryParamsTimeSpan) params;
after = time.getStartTime();
before = time.getEndTime();
}
int pageLength = 200;
int page = 0;
if (params instanceof TradeHistoryParamPaging) {
TradeHistoryParamPaging tradeHistoryParamPaging = (TradeHistoryParamPaging) params;
pageLength = tradeHistoryParamPaging.getPageLength();
page = tradeHistoryParamPaging.getPageNumber();
}
return TheRockAdapters.adaptUserTrades(getTheRockUserTrades(pairParams.getCurrencyPair(), sinceTradeId, after, before, pageLength, page),
pairParams.getCurrencyPair());
}
@Override
public TradeHistoryParams createTradeHistoryParams() {
throw new NotYetImplementedForExchangeException();
}
@Override
public OpenOrdersParams createOpenOrdersParams() {
return new TheRockOpenOrdersParams();
}
}
|
package net.geforcemods.securitycraft.renderers;
import net.geforcemods.securitycraft.SCContent;
import net.geforcemods.securitycraft.tileentity.TileEntityKeypadChest;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class ItemKeypadChestRenderer extends TileEntityItemStackRenderer {
private static final TileEntityKeypadChest DUMMY = new TileEntityKeypadChest();
@Override
public void renderByItem(ItemStack item) {
Block block = Block.getBlockFromItem(item.getItem());
if (block == SCContent.keypadChest)
TileEntityRendererDispatcher.instance.renderAsItem(DUMMY);
else
super.renderByItem(item);
}
}
|
package ch.uzh.csg.paymentlib.messages;
//TODO: javadoc
public class PaymentMessage {
public static final int HEADER_LENGTH = 1;
private static final byte DEFAULT = 0x00;
private static final byte ERROR = 0x01; // if not set, then PROCEED
private static final byte PAYER = 0x02; // if not set, then PAYEE
// data
private byte[] payload = new byte[0];
private int header = DEFAULT;
public PaymentMessage error() {
header = header | ERROR;
return this;
}
public boolean isError() {
return (header & ERROR) == ERROR;
}
public PaymentMessage payer() {
header = header | PAYER;
return this;
}
public boolean isPayer() {
return (header & PAYER) == PAYER;
}
public PaymentMessage payee() {
header = header & ~PAYER;
return this;
}
public boolean isPayee() {
return (header & PAYER) != PAYER;
}
public PaymentMessage payload(byte[] payload) {
if (payload == null || payload.length == 0)
throw new IllegalArgumentException("payload cannot be null or empty");
this.payload = payload;
return this;
}
public byte[] payload() {
return payload;
}
// serialization
public byte[] bytes() {
final int len = payload.length;
byte[] output = new byte[HEADER_LENGTH + len];
output[0] = (byte) header;
System.arraycopy(payload, 0, output, HEADER_LENGTH, len);
return output;
}
public PaymentMessage bytes(byte[] input) {
final int len = input.length;
if (!isEmpty())
throw new IllegalArgumentException("This message is not empty. You cannot overwrite the content. Instantiate a new object.");
if (input == null || len < HEADER_LENGTH)
throw new IllegalArgumentException("The input is null or does not contain enough data.");
header = input[0];
if (len > HEADER_LENGTH) {
payload = new byte[len - HEADER_LENGTH];
System.arraycopy(input, HEADER_LENGTH, payload, 0, len - HEADER_LENGTH);
}
return this;
}
private boolean isEmpty() {
return header == 0 && payload.length == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("PaymentMsg: ");
sb.append("head: ").append(Integer.toHexString(header));
sb.append(", len:").append(payload.length);
return sb.toString();
}
}
|
package com.java110.api.listener.users;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.listener.AbstractServiceApiDataFlowListener;
import com.java110.common.constant.CommonConstant;
import com.java110.common.constant.ServiceCodeConstant;
import com.java110.common.exception.ListenerExecuteException;
import com.java110.common.util.Assert;
import com.java110.common.util.StringUtil;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.factory.DataFlowFactory;
import com.java110.entity.center.AppService;
import com.java110.event.service.api.ServiceDataFlowEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import java.util.HashMap;
import java.util.Map;
@Java110Listener("queryStaffByUserNameServiceListener")
public class QueryStaffByUserNameServiceListener extends AbstractServiceApiDataFlowListener {
private final static Logger logger = LoggerFactory.getLogger(QueryStaffByUserNameServiceListener.class);
@Override
public int getOrder() {
return 0;
}
@Override
public String getServiceCode() {
return ServiceCodeConstant.SERVICE_CODE_QUERY_STAFF_BY_NAME;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.GET;
}
/**
*
* @param event
*/
@Override
public void soService(ServiceDataFlowEvent event) throws ListenerExecuteException{
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
JSONObject data = dataFlowContext.getReqJson();
logger.debug("{}",JSONObject.toJSONString(dataFlowContext));
Assert.hasKeyAndValue(data,"storeId","storeId");
Assert.hasKeyAndValue(data,"name","name");
ResponseEntity<String> responseEntity = null;
JSONObject resultJson = JSONObject.parseObject("{\"total:\":10,\"datas\":[]}");
responseEntity = super.callService(dataFlowContext,ServiceCodeConstant.SERVICE_CODE_QUERY_USER_BY_NAME,data);
if(responseEntity.getStatusCode() != HttpStatus.OK){
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String useIds = getUserIds(responseEntity,dataFlowContext);
if(StringUtil.isEmpty(useIds)){
responseEntity = new ResponseEntity<String>(resultJson.toJSONString(),HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONArray userInfos = getUserInfos(responseEntity);
Map<String,String> paramIn = new HashMap<>();
paramIn.put("userIds",useIds);
paramIn.put("storeId",data.getString("storeId"));
//userId
responseEntity = super.callService(dataFlowContext,ServiceCodeConstant.SERVICE_CODE_QUERY_STOREUSER_BYUSERIDS,paramIn);
if(responseEntity.getStatusCode() != HttpStatus.OK){
return ;
}
resultJson.put("datas",getStaffUsers(userInfos,responseEntity));
responseEntity = new ResponseEntity<String>(resultJson.toJSONString(),HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}
/**
*
* @param userInfos
* @param responseEntity ID
* @return
*/
private JSONArray getStaffUsers(JSONArray userInfos,ResponseEntity<String> responseEntity ){
JSONObject storeUserInfo = null;
JSONArray newStaffUsers = new JSONArray();
JSONArray storeUsers = JSONObject.parseObject(responseEntity.getBody().toString()).getJSONArray("storeUsers");
if(storeUsers == null || storeUsers.size() < 1){
return newStaffUsers;
}
for(int storeUserIndex = 0 ;storeUserIndex < storeUsers.size();storeUserIndex++){
storeUserInfo = storeUsers.getJSONObject(storeUserIndex);
for(int userIndex = 0; userIndex < userInfos.size();userIndex ++){
if(userInfos.getJSONObject(userIndex).getString("userId").equals(storeUserInfo.getString("userId"))){
newStaffUsers.add(userInfos.getJSONObject(userIndex));
}
}
}
return newStaffUsers;
}
/**
* ID
*
* 123,456,567
* @param responseEntity
* @param dataFlowContext
* @return
*/
private String getUserIds(ResponseEntity<String> responseEntity,DataFlowContext dataFlowContext){
JSONObject userInfo = null;
String userId = "";
JSONArray resultInfo = JSONObject.parseObject(responseEntity.getBody().toString()).getJSONArray("users");
if(resultInfo == null || resultInfo.size() < 1){
return userId;
}
for(int userIndex = 0 ;userIndex < resultInfo.size();userIndex++){
userInfo = resultInfo.getJSONObject(userIndex);
userId += (userInfo.getString("userId") +",");
}
userId = userId.length()>0?userId.substring(0,userId.lastIndexOf(",")):userId;
return userId;
}
/**
*
* @param responseEntity
* @return
*/
private JSONArray getUserInfos(ResponseEntity<String> responseEntity){
JSONArray resultInfo = JSONObject.parseObject(responseEntity.getBody().toString()).getJSONArray("users");
if(resultInfo == null || resultInfo.size() < 1){
return null;
}
return resultInfo;
}
/**
*
* @param tmpObj
*/
private void queryUserInfoByUserId( DataFlowContext dataFlowContext,JSONObject tmpObj,AppService appService){
String userId = tmpObj.getString("userId");
if(StringUtil.isEmpty(userId)){
return ;
}
ResponseEntity responseEntity= null;
String requestUrl = appService.getUrl();
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(),ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
//userId
requestUrl = requestUrl + "?userId="+userId;
dataFlowContext.getRequestHeaders().put("REQUEST_URL",requestUrl);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
doRequest(dataFlowContext,appService,httpEntity);
responseEntity = dataFlowContext.getResponseEntity();
if(responseEntity.getStatusCode() != HttpStatus.OK){
throw new ListenerExecuteException(1999," "+responseEntity.getBody());
}
tmpObj.putAll(JSONObject.parseObject(responseEntity.getBody().toString()));
}
}
|
package org.broadleafcommerce.order.service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.mail.MethodNotSupportedException;
import javax.persistence.NoResultException;
import org.broadleafcommerce.catalog.domain.Category;
import org.broadleafcommerce.catalog.domain.Product;
import org.broadleafcommerce.catalog.domain.Sku;
import org.broadleafcommerce.catalog.service.CatalogService;
import org.broadleafcommerce.offer.domain.Offer;
import org.broadleafcommerce.order.dao.FulfillmentGroupDao;
import org.broadleafcommerce.order.dao.FulfillmentGroupItemDao;
import org.broadleafcommerce.order.dao.OrderDao;
import org.broadleafcommerce.order.dao.OrderItemDao;
import org.broadleafcommerce.order.dao.PaymentInfoDao;
import org.broadleafcommerce.order.domain.FulfillmentGroup;
import org.broadleafcommerce.order.domain.FulfillmentGroupItem;
import org.broadleafcommerce.order.domain.Order;
import org.broadleafcommerce.order.domain.OrderItem;
import org.broadleafcommerce.order.domain.PaymentInfo;
import org.broadleafcommerce.pricing.service.PricingService;
import org.broadleafcommerce.profile.dao.AddressDao;
import org.broadleafcommerce.profile.domain.Customer;
import org.broadleafcommerce.type.FulfillmentGroupType;
import org.broadleafcommerce.type.OrderStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("orderService")
public class OrderServiceImpl implements OrderService {
@Resource
private OrderDao orderDao;
@Resource
private OrderItemDao orderItemDao;
@Resource
private PaymentInfoDao paymentInfoDao;
@Resource
private FulfillmentGroupDao fulfillmentGroupDao;
@Resource
private FulfillmentGroupItemDao fulfillmentGroupItemDao;
@Resource
private AddressDao addressDao;
@Resource
private PricingService pricingService;
@Resource
private CatalogService catalogService;
private boolean rollupOrderItems = true;
private boolean moveNamedOrderItems = true;
private boolean deleteEmptyNamedOrders = true;
@Override
public Order createNamedOrderForCustomer(String name, Customer customer) {
Order namedOrder = orderDao.create();
namedOrder.setCustomer(customer);
namedOrder.setName(name);
namedOrder.setStatus(OrderStatus.NAMED);
return orderDao.maintianOrder(namedOrder);
}
@Override
public Order findOrderById(Long orderId) {
return orderDao.readOrderById(orderId);
}
@Override
public Order findCartForCustomer(Customer customer, boolean createIfDoesntExist) {
return orderDao.readCartForCustomer(customer, createIfDoesntExist);
}
@Override
public Order findCartForCustomer(Customer customer) {
return orderDao.readCartForCustomer(customer, false);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<Order> findOrdersForCustomer(Customer customer) {
return orderDao.readOrdersForCustomer(customer.getId());
}
@Override
public List<Order> findOrdersForCustomer(Customer customer, OrderStatus status) {
return orderDao.readOrdersForCustomer(customer, status);
}
@Override
public Order findNamedOrderForCustomer(String name, Customer customer) {
return orderDao.readNamedOrderForCustomer(customer, name);
}
@Override
public FulfillmentGroup findDefaultFulfillmentGroupForOrder(Order order) {
FulfillmentGroup fg = null;
try {
fg = fulfillmentGroupDao.readDefaultFulfillmentGroupForOrder(order);
} catch (NoResultException nre) {
fg = createDefaultFulfillmentGroup(order);
fg = fulfillmentGroupDao.maintainDefaultFulfillmentGroup(fg);
}
if (fg.getFulfillmentGroupItems() == null || fg.getFulfillmentGroupItems().size() == 0) {
// Only Default fulfillment group has been created so
// add all orderItems for order to group
List<OrderItem> orderItems = order.getOrderItems();
for (OrderItem orderItem : orderItems) {
FulfillmentGroupItem fgi = this.createFulfillmentGroupItemFromOrderItem(orderItem, fg.getId());
fgi = fulfillmentGroupItemDao.maintainFulfillmentGroupItem(fgi);
fg.addFulfillmentGroupItem(fgi);
}
// Go ahead and persist it so we don't have to do this later
fulfillmentGroupDao.maintainDefaultFulfillmentGroup(fg);
}
return fg;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public OrderItem addSkuToOrder(Order order, Sku sku, int quantity) {
return addSkuToOrder(order, sku, null, null, quantity);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public OrderItem addSkuToOrder(Order order, Sku sku, Product product, Category category, int quantity) {
OrderItem orderItem = addSkuToLocalOrder(order, sku, product, category, quantity);
return maintainOrderItem(orderItem);
}
@Override
public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, int quantity) {
Order order = orderDao.readOrderById(orderId);
Sku sku = catalogService.findSkuById(skuId);
Product product = catalogService.findProductById(productId);
Category category = catalogService.findCategoryById(categoryId);
return addSkuToOrder(order, sku, product, category, quantity);
}
@Override
public List<OrderItem> addSkusToOrder(Map<String, Integer> skuIdQtyMap, Order order) throws MethodNotSupportedException {
// for (String skuId : skuIdQtyMap.keySet()) {
// Sku sku = catalogservice.findSkuById(skuId);
// // TODO Implement if needed
// return null;
throw new MethodNotSupportedException();
}
@Override
public OrderItem addItemToCartFromNamedOrder(Order order, Sku sku, int quantity) {
removeItemFromOrder(order, sku.getId());
return addSkuToOrder(order, sku, quantity);
}
@Override
public Order addAllItemsToCartFromNamedOrder(Order namedOrder) {
Order cartOrder = orderDao.readCartForCustomer(namedOrder.getCustomer(), true);
for (OrderItem orderItem : namedOrder.getOrderItems()) {
if (moveNamedOrderItems) {
removeItemFromOrder(namedOrder, orderItem.getId());
}
addSkuToOrder(cartOrder, orderItem.getSku(), orderItem.getQuantity());
}
return cartOrder;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment) {
payment.setOrder(order);
if (payment.getAddress() != null && payment.getAddress().getId() == null) {
payment.setAddress(addressDao.maintainAddress(payment.getAddress()));
}
return paymentInfoDao.maintainPaymentInfo(payment);
}
@Override
public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup) {
FulfillmentGroup dfg;
try {
dfg = fulfillmentGroupDao.readDefaultFulfillmentGroupForOrder(order);
} catch (NoResultException nre) {
// This is the first fulfillment group added so make it the
// default one
// order.setFulfillmentGroups(new Vector<FulfillmentGroup>([fg]));
FulfillmentGroup newDfg = findDefaultFulfillmentGroupForOrder(order);
order.addFulfillmentGroup(newDfg);
newDfg.setAddress(fulfillmentGroup.getAddress());
fulfillmentGroupDao.maintainDefaultFulfillmentGroup(newDfg);
return newDfg;
}
// if(dfg == null){
// }else
if (dfg.getId().equals(fulfillmentGroup.getId())) {
// API user is trying to re-add the default fulfillment group
// to the same order
// um....treat it as update/maintain for now
return fulfillmentGroupDao.maintainDefaultFulfillmentGroup(fulfillmentGroup);
} else {
// API user is adding a new fulfillment group to the order
fulfillmentGroup.setOrderId(order.getId());
// 1) For each item in the new fulfillment group
if (fulfillmentGroup.getFulfillmentGroupItems() != null) {
for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {
// 2) Find the item's existing fulfillment group
for (FulfillmentGroup fg : order.getFulfillmentGroups()) {
for (FulfillmentGroupItem tempFgi : fg.getFulfillmentGroupItems()) {
if (tempFgi.getOrderItem().getId().equals(fgItem.getId())) {
// 3) remove item from it's existing fulfillment
// group
fg.getFulfillmentGroupItems().remove(fg);
}
}
fulfillmentGroupDao.maintainFulfillmentGroup(fg);
}
}
}
FulfillmentGroup returnedFg = fulfillmentGroupDao.maintainFulfillmentGroup(fulfillmentGroup);
order.addFulfillmentGroup(returnedFg);
maintainOrder(order);
return returnedFg;
}
}
@Override
public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity) {
FulfillmentGroupItem fgi = null;
Order order = orderDao.readOrderById(item.getOrderId());
if (fulfillmentGroup.getId() == null) {
// API user is trying to add an item to a fulfillment group not
// created
fulfillmentGroup = addFulfillmentGroupToOrder(order, fulfillmentGroup);
// fulfillmentGroup.setFulfillmentGroupItems(new
// ArrayList<FulfillmentGroupItem>());
}
// API user is trying to add an item to an existing fulfillment group
// Steps are
order = orderDao.readOrderById(item.getOrderId());
// 1) Find the item's existing fulfillment group
for (Iterator<FulfillmentGroup> fgIterator = order.getFulfillmentGroups().iterator(); fgIterator.hasNext();) {
FulfillmentGroup fg = fgIterator.next();
if (fg.getFulfillmentGroupItems() != null) {
List<FulfillmentGroupItem> itemsToRemove = new ArrayList<FulfillmentGroupItem>();
for (Iterator<FulfillmentGroupItem> fgiIterator = fg.getFulfillmentGroupItems().iterator(); fgiIterator.hasNext();) {
FulfillmentGroupItem tempFgi = fgiIterator.next();
if (tempFgi.getOrderItem().getId().equals(item.getId())) {
fgi = tempFgi;
// 2) remove item from it's existing fulfillment group
itemsToRemove.add(fgi);
}
}
if (!itemsToRemove.isEmpty()) {
fg.getFulfillmentGroupItems().removeAll(itemsToRemove);
fulfillmentGroupDao.maintainFulfillmentGroup(fg);
}
}
}
if (fgi == null) {
fgi = createFulfillmentGroupItemFromOrderItem(item, fulfillmentGroup.getId());
}
// 3) add the item to the new fulfillment group
if (fulfillmentGroup.getType() == null) {
fulfillmentGroup.addFulfillmentGroupItem(fgi);
}
fulfillmentGroup = fulfillmentGroupDao.maintainFulfillmentGroup(fulfillmentGroup);
fgi.setFulfillmentGroupId(fulfillmentGroup.getId());
fgi = fulfillmentGroupItemDao.maintainFulfillmentGroupItem(fgi);
return fulfillmentGroup;
}
@Override
public Order addOfferToOrder(Order order, String offerCode) {
throw new UnsupportedOperationException();
}
@Override
public FulfillmentGroup updateFulfillmentGroup(FulfillmentGroup fulfillmentGroup) {
return fulfillmentGroupDao.maintainFulfillmentGroup(fulfillmentGroup);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public OrderItem updateItemInOrder(Order order, OrderItem item) {
// This isn't quite right. It will need to be changed later to reflect
// the exact requirements we want.
// item.setQuantity(quantity);
// item.setOrder(order);
return maintainOrderItem(item);
}
@Override
public List<OrderItem> updateItemsInOrder(Order order, List<OrderItem> orderItems) {
for (OrderItem orderItem : orderItems) {
// orderItem.setOrder(order);
// TODO change this so it persists them all at once instead of each
// at a time
maintainOrderItem(orderItem);
}
return orderItems;
}
@Override
public OrderItem moveItemToCartFromNamedOrder(Order namedOrder, Long orderItemId, int quantity) {
OrderItem orderItem = orderItemDao.readOrderItemById(orderItemId);
Order cartOrder = orderDao.readCartForCustomer(namedOrder.getCustomer(), true);
if (moveNamedOrderItems) {
Order updatedNamedOrder = removeItemFromOrder(namedOrder, orderItem);
if (updatedNamedOrder.getOrderItems().size() == 0 && deleteEmptyNamedOrders) {
orderDao.deleteOrderForCustomer(updatedNamedOrder);
}
}
return addSkuToOrder(cartOrder, orderItem.getSku(), orderItem.getProduct(), orderItem.getCategory(), quantity);
}
@Override
public Order moveAllItemsToCartFromNamedOrder(Order namedOrder) {
Order cartOrder = addAllItemsToCartFromNamedOrder(namedOrder);
if (deleteEmptyNamedOrders) {
orderDao.deleteOrderForCustomer(namedOrder);
}
return cartOrder;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Order removeItemFromOrder(Order order, long orderItemId) {
OrderItem orderItem = orderItemDao.readOrderItemById(orderItemId);
if (orderItem == null) {
return null;
}
removeOrderItemFromFullfillmentGroup(order, orderItem);
orderItemDao.deleteOrderItem(orderItem);
order = pricingService.executePricing(order);
return orderDao.readOrderById(order.getId());
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Order removeItemFromOrder(Order order, OrderItem item) {
orderItemDao.deleteOrderItem(item);
removeOrderItemFromFullfillmentGroup(order, item);
order = pricingService.executePricing(order);
order.getOrderItems().remove(item);
orderDao.maintianOrder(order);
return orderDao.readOrderById(order.getId());
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void removeAllFulfillmentGroupsFromOrder(Order order) {
if (order.getFulfillmentGroups() != null) {
for (Iterator<FulfillmentGroup> iterator = order.getFulfillmentGroups().iterator(); iterator.hasNext();) {
FulfillmentGroup fulfillmentGroup = iterator.next();
iterator.remove();
fulfillmentGroupDao.removeFulfillmentGroupForOrder(order, fulfillmentGroup);
}
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup) {
order.getFulfillmentGroups().remove(fulfillmentGroup);
maintainOrder(order);
fulfillmentGroupDao.removeFulfillmentGroupForOrder(order, fulfillmentGroup);
}
@Override
public Order removeOfferFromOrder(Order order, Offer offer) {
throw new UnsupportedOperationException();
}
@Override
public void removeNamedOrderForCustomer(String name, Customer customer) {
Order namedOrder = findNamedOrderForCustomer(name, customer);
orderDao.deleteOrderForCustomer(namedOrder);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Order confirmOrder(Order order) {
// TODO Other actions needed to complete order
// (such as calling something to make sure the order is fulfilled
// somehow).
// Code below is only a start.
return orderDao.submitOrder(order);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void cancelOrder(Order order) {
orderDao.deleteOrderForCustomer(order);
}
protected Order maintainOrder(Order order) {
order = pricingService.executePricing(order);
return orderDao.maintianOrder(order);
}
protected OrderItem maintainOrderItem(OrderItem orderItem) {
orderItem.setPrice(orderItem.getSku().getSalePrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
OrderItem returnedOrderItem = orderItemDao.maintainOrderItem(orderItem);
// maintainOrder(orderItem.getOrder());
return returnedOrderItem;
}
protected FulfillmentGroup createDefaultFulfillmentGroup(Order order) {
FulfillmentGroup newFg = fulfillmentGroupDao.createDefault();
newFg.setOrderId(order.getId());
newFg.setType(FulfillmentGroupType.DEFAULT);
// for (OrderItem orderItem : order.getOrderItems()) {
// newFg = addItemToFulfillmentGroup(orderItem, newFg,
// orderItem.getQuantity());
return newFg;
}
protected FulfillmentGroupItem createFulfillmentGroupItemFromOrderItem(OrderItem orderItem, Long fulfillmentGroupId) {
FulfillmentGroupItem fgi = fulfillmentGroupItemDao.create();
fgi.setFulfillmentGroupId(fulfillmentGroupId);
fgi.setOrderItem(orderItem);
fgi.setQuantity(orderItem.getQuantity());
return fgi;
}
protected OrderItem addSkuToLocalOrder(Order order, Sku sku, Product product, Category category, int quantity) {
OrderItem orderItem = null;
List<OrderItem> orderItems = order.getOrderItems();
if (orderItems != null && rollupOrderItems) {
for (OrderItem orderItem2 : orderItems) {
if (orderItem2.getSku().getId().equals(sku.getId())) {
orderItem = orderItem2;
break;
}
}
}
if (orderItem == null) {
// orderItem = new OrderItem();
orderItem = orderItemDao.create();
}
orderItem.setProduct(product);
orderItem.setCategory(category);
orderItem.setSku(sku);
orderItem.setQuantity(orderItem.getQuantity() + quantity);
// orderItem.setOrder(order);
orderItem.setOrderId(order.getId());
return orderItem;
}
protected void removeOrderItemFromFullfillmentGroup(Order order, OrderItem orderItem) {
List<FulfillmentGroup> fulfillmentGroups = order.getFulfillmentGroups();
for (FulfillmentGroup fulfillmentGroup : fulfillmentGroups) {
List<FulfillmentGroupItem> itemsToRemove = new ArrayList<FulfillmentGroupItem>();
List<FulfillmentGroupItem> fgItems = fulfillmentGroup.getFulfillmentGroupItems();
for (FulfillmentGroupItem fulfillmentGroupItem : fgItems) {
if(fulfillmentGroupItem.getOrderItem().equals(orderItem)) {
itemsToRemove.add(fulfillmentGroupItem);
}
}
if (!itemsToRemove.isEmpty()) {
for (FulfillmentGroupItem fgi : itemsToRemove) {
fulfillmentGroupItemDao.deleteFulfillmentGroupItem(fgi);
}
fulfillmentGroup.getFulfillmentGroupItems().removeAll(itemsToRemove);
}
}
}
/*
* (non-Javadoc)
* @seeorg.broadleafcommerce.order.service.OrderService#mergeCart(org.
* broadleafcommerce.profile.domain.Customer, java.lang.Long)
*/
@Override
public MergeCartResponse mergeCart(Customer customer, Long anonymousCartId) {
MergeCartResponse mergeCartResponse = new MergeCartResponse();
Order customerCart = findCartForCustomer(customer, false);
// reconstruct cart items (make sure they are valid)
ReconstructCartResponse reconstructCartResponse = reconstructCart(customer);
mergeCartResponse.setRemovedItems(reconstructCartResponse.getRemovedItems());
customerCart = reconstructCartResponse.getOrder();
// add anonymous cart items (make sure they are valid)
if ((customerCart == null || !customerCart.getId().equals(anonymousCartId)) && anonymousCartId != null) {
Order anonymousCart = findOrderById(anonymousCartId);
if (anonymousCart != null && anonymousCart.getOrderItems() != null && !anonymousCart.getOrderItems().isEmpty()) {
if (customerCart == null) {
customerCart = findCartForCustomer(customer, true);
}
// TODO improve merge algorithm to support various requirements
// currently we'll just add items
for (OrderItem orderItem : anonymousCart.getOrderItems()) {
if (orderItem.getSku().isActive(orderItem.getProduct(), orderItem.getCategory())) {
addSkuToOrder(customerCart, orderItem.getSku(), orderItem.getProduct(), orderItem.getCategory(), orderItem.getQuantity());
mergeCartResponse.getAddedItems().add(orderItem);
} else {
mergeCartResponse.getRemovedItems().add(orderItem);
}
removeItemFromOrder(anonymousCart, orderItem.getId());
orderDao.deleteOrderForCustomer(anonymousCart);
}
}
}
mergeCartResponse.setOrder(customerCart);
return mergeCartResponse;
}
/*
* (non-Javadoc)
* @see
* org.broadleafcommerce.order.service.OrderService#reconstructCart(org.
* broadleafcommerce.profile.domain.Customer)
*/
@Override
public ReconstructCartResponse reconstructCart(Customer customer) {
ReconstructCartResponse reconstructCartResponse = new ReconstructCartResponse();
Order customerCart = findCartForCustomer(customer, false);
if (customerCart != null) {
for (OrderItem orderItem : customerCart.getOrderItems()) {
if (!orderItem.getSku().isActive(orderItem.getProduct(), orderItem.getCategory())) {
reconstructCartResponse.getRemovedItems().add(orderItem);
removeItemFromOrder(customerCart, orderItem.getId());
}
}
}
reconstructCartResponse.setOrder(customerCart);
return reconstructCartResponse;
}
@Override
public List<PaymentInfo> readPaymentInfosForOrder(Order order) {
return paymentInfoDao.readPaymentInfosForOrder(order);
}
public boolean isRollupOrderItems() {
return rollupOrderItems;
}
public void setRollupOrderItems(boolean rollupOrderItems) {
this.rollupOrderItems = rollupOrderItems;
}
public boolean isMoveNamedOrderItems() {
return moveNamedOrderItems;
}
public void setMoveNamedOrderItems(boolean moveNamedOrderItems) {
this.moveNamedOrderItems = moveNamedOrderItems;
}
public boolean isDeleteEmptyNamedOrders() {
return deleteEmptyNamedOrders;
}
public void setDeleteEmptyNamedOrders(boolean deleteEmptyNamedOrders) {
this.deleteEmptyNamedOrders = deleteEmptyNamedOrders;
}
}
|
package com.microlands.android.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import java.util.UUID;
/**
* A simple {@link Fragment} subclass.
*/
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
public CrimeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
UUID uuid = (UUID) getActivity().getIntent().getSerializableExtra(CrimeActivity.EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(uuid);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText) view.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) view.findViewById(R.id.crime_date);
mDateButton.setText(android.text.format.DateFormat.format("EEE, d MMM yyyy HH:mm:ss Z", mCrime.getDate()));
mDateButton.setEnabled(false);
mSolvedCheckBox = (CheckBox) view.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return view;
}
}
|
// Test file to check for correct functionality of the local database.
// Adding a user will randomly add one of three pre-generated users into
// the list, and removing a user will remove the user with the lowest id
// number
package com.github.tbporter.cypher_sydekick.database;
import java.util.List;
import java.util.Random;
import com.github.tbporter.cypher_sydekick.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
public class TestDatabaseActivity extends ListActivity {
private UserKeyDOA datasource;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database_client);
datasource = new UserKeyDOA(this);
datasource.open();
List<String> values = datasource.getAllUsers();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
@SuppressWarnings("unchecked")
ArrayAdapter<UserKey> adapter = (ArrayAdapter<UserKey>) getListAdapter();
UserKey username = null;
switch (view.getId()) {
case R.id.add:
String[] namelist = new String[] { "Ben", "Travis", "Alex" };
String[] keylist = new String[] { "FA8400DB", "FA8400DC", "FA8400DD" };
int nextInt = new Random().nextInt(3);
// save the new users to the database
username = datasource.createUser(namelist[nextInt], keylist[nextInt]);
adapter.add(username);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
username = (UserKey) getListAdapter().getItem(0);
//datasource.deleteUser(username);
adapter.remove(username);
}
break;
}
adapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
datasource.open();
super.onResume();
}
@Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
|
package org.splevo.jamopp.diffing;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.EMFCompare;
import org.eclipse.emf.compare.diff.DefaultDiffEngine;
import org.eclipse.emf.compare.diff.FeatureFilter;
import org.eclipse.emf.compare.diff.IDiffEngine;
import org.eclipse.emf.compare.diff.IDiffProcessor;
import org.eclipse.emf.compare.match.DefaultMatchEngine;
import org.eclipse.emf.compare.match.IMatchEngine;
import org.eclipse.emf.compare.match.impl.MatchEngineFactoryRegistryImpl;
import org.eclipse.emf.compare.postprocessor.BasicPostProcessorDescriptorImpl;
import org.eclipse.emf.compare.postprocessor.IPostProcessor;
import org.eclipse.emf.compare.postprocessor.PostProcessorDescriptorRegistryImpl;
import org.eclipse.emf.compare.scope.IComparisonScope;
import org.eclipse.emf.compare.utils.EqualityHelper;
import org.eclipse.emf.compare.utils.IEqualityHelper;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.emftext.commons.layout.LayoutPackage;
import org.emftext.language.java.JavaPackage;
import org.splevo.diffing.Differ;
import org.splevo.diffing.DiffingException;
import org.splevo.diffing.DiffingNotSupportedException;
import org.splevo.diffing.match.HierarchicalMatchEngine.EqualityStrategy;
import org.splevo.diffing.match.HierarchicalMatchEngine.IgnoreStrategy;
import org.splevo.diffing.match.HierarchicalMatchEngineFactory;
import org.splevo.diffing.match.HierarchicalStrategyResourceMatcher;
import org.splevo.extraction.SoftwareModelExtractionException;
import org.splevo.jamopp.diffing.diff.JaMoPPDiffBuilder;
import org.splevo.jamopp.diffing.diff.JaMoPPFeatureFilter;
import org.splevo.jamopp.diffing.match.JaMoPPEqualityHelper;
import org.splevo.jamopp.diffing.match.JaMoPPEqualityStrategy;
import org.splevo.jamopp.diffing.match.JaMoPPIgnoreStrategy;
import org.splevo.jamopp.diffing.postprocessor.JaMoPPPostProcessor;
import org.splevo.jamopp.diffing.scope.JavaModelMatchScope;
import org.splevo.jamopp.diffing.scope.PackageIgnoreChecker;
import org.splevo.jamopp.diffing.similarity.SimilarityChecker;
import org.splevo.jamopp.extraction.JaMoPPSoftwareModelExtractor;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Differ for JaMoPP software models.
*
* <p>
* <strong>Ignored files</strong><br>
* By default, the differ ignores all package-info.java.xmi model files.<br>
* The option {@link JaMoPPDiffer#OPTION_JAMOPP_IGNORE_FILES} can be provided as diffing option to
* the doDiff() method to change this default behavior.
* </p>
*
* @author Benjamin Klatt
*
*/
public class JaMoPPDiffer implements Differ {
/** Option key for java packages to ignore. */
public static final String OPTION_JAMOPP_IGNORE_FILES = "JaMoPP.Files.to.ignore";
/**
* Option key for java package patterns to ignore.<br>
* The purpose of this option is to exclude source code packages from being considered during
* the diff analysis.
*
*/
public static final String OPTION_JAVA_IGNORE_PACKAGES = "JaMoPP.Java.Packages.to.ignore";
/**
* Option key for package mappings.<br>
* The purpose of this option is to normalize the package of the integrated variant.<br>
* <p>
* Example:<br>
* If the original code contains a package named:<br>
* <tt>org.example.client</tt><br>
* and the customized code contains a package named:<br>
* <tt>org.example.customer.client</tt><br>
* the mapping can be used to normalize the latter package to the former.
* </p>
*
* <p>
* A rule is specified per line.<br>
* Each line contains a pair of search and replace separated with a pipe ("|").<br>
* For example:<br>
* org.example.customer.client|org.example.client<br>
* org.example.customer.server|org.example.server
* </p>
*/
public static final String OPTION_JAVA_PACKAGE_NORMALIZATION = "JaMoPP.Java.Package.Normalization.Pattern";
private static final String LABEL = "JaMoPP Java Differ";
private static final String ID = "org.splevo.jamopp.differ";
private static Logger logger = Logger.getLogger(JaMoPPDiffer.class);
/**
* Load the source models from the according directories and perform the difference analysis of
* the loaded {@link ResourceSet}s. <br>
* {@inheritDoc}
*
* @return null if no supported source models available.
* @throws DiffingNotSupportedException
* Thrown if a diffing cannot be done for the provided models.
*/
@Override
public Comparison doDiff(java.net.URI leadingModelDirectory, java.net.URI integrationModelDirectory,
Map<String, String> diffingOptions) throws DiffingException, DiffingNotSupportedException {
final List<String> ignoreFiles;
if (diffingOptions.containsKey(OPTION_JAMOPP_IGNORE_FILES)) {
final String diffingRuleRaw = diffingOptions.get(OPTION_JAMOPP_IGNORE_FILES);
final String[] parts = diffingRuleRaw.split(System.getProperty("line.separator"));
ignoreFiles = Lists.newArrayList();
for (final String rule : parts) {
ignoreFiles.add(rule);
}
} else {
ignoreFiles = Lists.asList("package-info.java", new String[] {});
}
logger.info("Load source models");
ResourceSet resourceSetLeading = loadResourceSetRecursively(leadingModelDirectory, ignoreFiles);
ResourceSet resourceSetIntegration = loadResourceSetRecursively(integrationModelDirectory, ignoreFiles);
return doDiff(resourceSetLeading, resourceSetIntegration, diffingOptions);
}
/**
* Diffing the models contained in the provided resource sets.<br>
*
* {@inheritDoc}
*
* @return null if no supported source models available.
* @throws DiffingNotSupportedException
* Thrown if no reasonable JaMoPP model is contained in the resource sets.
*/
@Override
public Comparison doDiff(ResourceSet resourceSetLeading, ResourceSet resourceSetIntegration,
Map<String, String> diffingOptions) throws DiffingException, DiffingNotSupportedException {
List<String> ignorePackages = buildIgnorePackageList(diffingOptions);
PackageIgnoreChecker packageIgnoreChecker = new PackageIgnoreChecker(ignorePackages);
EMFCompare comparator = initCompare(packageIgnoreChecker);
// Compare the two models
// In comparison, the left side is always the changed one.
// push in the integration model first
IComparisonScope scope = new JavaModelMatchScope(resourceSetIntegration, resourceSetLeading,
packageIgnoreChecker);
Comparison comparisonModel = comparator.compare(scope);
return comparisonModel;
}
/**
* Build the list of package ignore patterns from the provided diffing options.
*
* @param diffingOptions
* Diffing options to process.
* @return The list of patterns, maybe empty but never null.
*/
private List<String> buildIgnorePackageList(Map<String, String> diffingOptions) {
String diffingRuleRaw = diffingOptions.get(OPTION_JAVA_IGNORE_PACKAGES);
List<String> ignorePackages = Lists.newArrayList();
if (diffingRuleRaw != null) {
final String[] parts = diffingRuleRaw.split(System.getProperty("line.separator"));
for (final String rule : parts) {
ignorePackages.add(rule);
}
}
return ignorePackages;
}
/**
* Initialize the compare engine.
*
* @param packageIgnoreChecker
* The checker to decide if an element is within a package to ignore.
* @return The prepared emf compare engine.
*/
private EMFCompare initCompare(PackageIgnoreChecker packageIgnoreChecker) {
SimilarityChecker similarityChecker = new SimilarityChecker();
final LoadingCache<EObject, org.eclipse.emf.common.util.URI> cache = initEqualityCache();
IEqualityHelper equalityHelper = new JaMoPPEqualityHelper(cache, similarityChecker);
IMatchEngine.Factory.Registry matchEngineRegistry = initMatchEngine(equalityHelper, packageIgnoreChecker,
similarityChecker);
IPostProcessor.Descriptor.Registry<?> postProcessorRegistry = initPostProcessors(packageIgnoreChecker);
IDiffEngine diffEngine = initDiffEngine(packageIgnoreChecker);
EMFCompare comparator = initComparator(matchEngineRegistry, postProcessorRegistry, diffEngine);
return comparator;
}
/**
* Initialize a cache to be used by the equality helper.
*
* @return The ready to use cache.
*/
private LoadingCache<EObject, org.eclipse.emf.common.util.URI> initEqualityCache() {
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(
DefaultMatchEngine.DEFAULT_EOBJECT_URI_CACHE_MAX_SIZE);
final LoadingCache<EObject, org.eclipse.emf.common.util.URI> cache = EqualityHelper
.createDefaultCache(cacheBuilder);
return cache;
}
/**
* Initialize the post processors and build an according registry.
*
* @param packageIgnoreChecker
* The checker if an element belongs to an ignored package.
* @return The prepared registry with references to the post processors.
*/
private IPostProcessor.Descriptor.Registry<String> initPostProcessors(PackageIgnoreChecker packageIgnoreChecker) {
IPostProcessor customPostProcessor = new JaMoPPPostProcessor();
Pattern any = Pattern.compile(".*");
IPostProcessor.Descriptor descriptor = new BasicPostProcessorDescriptorImpl(customPostProcessor, any, any);
IPostProcessor.Descriptor.Registry<String> postProcessorRegistry = new PostProcessorDescriptorRegistryImpl<String>();
postProcessorRegistry.put(JaMoPPPostProcessor.class.getName(), descriptor);
return postProcessorRegistry;
}
/**
* Init the comparator instance to be used for comparison.
*
* @param matchEngineRegistry
* The registry containing the match engines to be used.
* @param postProcessorRegistry
* Registry for post processors to be executed.
* @param diffEngine
* The diff engine to run.
* @return The prepared comparator instance.
*/
private EMFCompare initComparator(IMatchEngine.Factory.Registry matchEngineRegistry,
IPostProcessor.Descriptor.Registry<?> postProcessorRegistry, IDiffEngine diffEngine) {
EMFCompare.Builder builder = EMFCompare.builder();
builder.setDiffEngine(diffEngine);
builder.setMatchEngineFactoryRegistry(matchEngineRegistry);
builder.setPostProcessorRegistry(postProcessorRegistry);
EMFCompare comparator = builder.build();
return comparator;
}
/**
* Initialize the diff engine with the diff processor and feature filters to be used.
*
* @param packageIgnoreChecker
* Checker to decide if an element is in a package to ignore.
* @return The ready-to-use diff engine.
*/
private IDiffEngine initDiffEngine(final PackageIgnoreChecker packageIgnoreChecker) {
IDiffProcessor diffProcessor = new JaMoPPDiffBuilder(packageIgnoreChecker);
IDiffEngine diffEngine = new DefaultDiffEngine(diffProcessor) {
@Override
protected FeatureFilter createFeatureFilter() {
return new JaMoPPFeatureFilter(packageIgnoreChecker);
}
};
return diffEngine;
}
/**
* Initialize and configure the match engines to be used.
*
* @param equalityHelper
* The equality helper to be used during the diff process.
* @param packageIgnoreChecker
* The package ignore checker to use in the match engine.
* @param similarityChecker
* The similarity checker to use in the match engine.
*
* @return The registry containing all prepared match engines
*/
private IMatchEngine.Factory.Registry initMatchEngine(IEqualityHelper equalityHelper,
PackageIgnoreChecker packageIgnoreChecker, SimilarityChecker similarityChecker) {
EqualityStrategy equalityStrategy = new JaMoPPEqualityStrategy(similarityChecker);
IgnoreStrategy ignoreStrategy = new JaMoPPIgnoreStrategy(packageIgnoreChecker);
IMatchEngine.Factory matchEngineFactory = new HierarchicalMatchEngineFactory(equalityHelper, equalityStrategy,
ignoreStrategy, new HierarchicalStrategyResourceMatcher());
matchEngineFactory.setRanking(20);
IMatchEngine.Factory.Registry matchEngineRegistry = new MatchEngineFactoryRegistryImpl();
matchEngineRegistry.add(matchEngineFactory);
return matchEngineRegistry;
}
@Override
public String getId() {
return ID;
}
@Override
public String getLabel() {
return LABEL;
}
@Override
public void init() {
JavaPackage.eINSTANCE.eClass();
LayoutPackage.eINSTANCE.eClass();
}
/**
* Recursively load all files within a directory into a resource set.
*
* @param baseDirectory
* The root directory to search files in.
* @param ignoreFiles
* A list of filenames to ignore during load.
* @return The prepared resource set.
*/
private ResourceSet loadResourceSetRecursively(java.net.URI baseDirectory, List<String> ignoreFiles) {
JaMoPPSoftwareModelExtractor extractor = new JaMoPPSoftwareModelExtractor();
List<URI> projectPaths = new ArrayList<URI>();
projectPaths.add(URI.createFileURI(new File(baseDirectory).getAbsolutePath()));
try {
return extractor.extractSoftwareModel(projectPaths, new NullProgressMonitor());
} catch (SoftwareModelExtractionException e) {
logger.error("Failed to load resource set", e);
}
return new ResourceSetImpl();
}
@Override
public Map<String, String> getAvailableConfigurations() {
Map<String, String> options = Maps.newHashMap();
options.put(OPTION_JAVA_IGNORE_PACKAGES, "java.*\njavax.*");
options.put(OPTION_JAMOPP_IGNORE_FILES, "package-info.java");
return options;
}
@Override
public int getOrderId() {
return 0;
}
}
|
package alma.ACS.MasterComponentImpl;
import java.util.logging.Logger;
/**
* Helper class that allows to synchronize the sending of events with the
* state changes due to previous events.
* Note that state changes occur asynchronously when triggered by activity states.
* <p>
* This class is abstracted from concrete state change notification APIs so that
* subclasses can be implemented as such listeners; they must call {@link #stateChangedNotify()}
* upon notification by the state machine.
*
* @author hsommer
* created Apr 30, 2004 9:50:34 AM
*/
public class StateChangeSemaphore
{
private volatile int notifCount = 0;
private volatile int minCount;
private Logger logger;
public StateChangeSemaphore(Logger logger) {
if (logger == null) {
// @TODO throw ex in ACS 7.0 which we can't do now in 6.0.3. Then remove all the checks for logger != null
}
this.logger = logger;
}
/**
* @deprecated as of ACS 6.0.3. Use {@link #StateChangeSemaphore(Logger)} instead.
*/
public StateChangeSemaphore() {
this(null);
}
/**
* To be called from state change listener method of subclass.
* <p>
* This call is expected to come from a different thread than the one that calls <code>waitForStateChanges</code>.
* Both methods are synchronized, but there will not be a deadlock, since <code>waitForStateChanges</code>
* yields ownership of the monitor when calling {@link Object#wait() wait}.
*/
protected synchronized void stateChangedNotify() {
if (logger != null) {
logger.finest("stateChangedNotify: called in thread '" + Thread.currentThread().getName() + "'.");
}
notifCount++;
if (notifCount >= minCount) {
// release thread that blocks on waitForStateChanges
notifyAll();
}
}
/**
* Blocks until the specified number of state change notifications have been received
* since last call to {@link #reset()}.
* <p>
* Does not block at all if at least <code>count</code> state change notifications
* have been received since the last call to <code>reset</code>. Otherwise only blocks until
* the missing number of notifications has arrived.
* Before returning, this method subtracts <code>count</code> from the internal counter for state change notifications,
* which allows a client to catch up with fast firing event notifications by calling this method several times.
* <p>
* Note that the "synchronized" modifier is required in order for the client thread
* to obtain ownership of this semaphore (i.e. its monitor),
* without which the thread synchronization would not work.
* See {@link Object#notify()} for an explanation.
*
* @param count number of state change notifications that must be received
* since last call to {@link #reset()}
* so that this call will return
* @throws InterruptedException
*/
public synchronized void waitForStateChanges(int count) throws InterruptedException {
if (logger != null) {
logger.finest("waitForStateChanges: called in thread '" + Thread.currentThread().getName() + "'.");
}
minCount = count;
// was stateChangedNotify called sufficiently often already?
while (notifCount < count) {
if (logger != null) {
logger.finest("waitForStateChanges: waiting for " + (count - notifCount) + " state change notification(s)");
}
// releases current thread's ownership of this StateChangeSemaphore's monitor, and blocks until other thread calls notify
wait();
// now our thread has re-obtained ownership of this StateChangeSemaphore's monitor, so the field notifCount is again ours.
}
notifCount = notifCount - count;
if (logger != null) {
logger.finest("waitForStateChanges: state change notification counter down at " + notifCount);
}
}
/**
* Resets the state change notification count.
* Must be called prior to sending a state event.
*/
public synchronized void reset() {
notifCount = 0;
}
}
|
package edu.oregonstate.kronquii.numinousnimbusandroid;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Act1 extends Activity {
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("TakePicture", "logging
final String dir;
Button postButton;
Button photoButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act1);
postButton = (Button) findViewById(R.id.postButton);
postButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Act1.this, "Uploading...", Toast.LENGTH_LONG).show();
new PostToImgur().execute("Pic.jpg");
}
});
photoButton = (Button) findViewById(R.id.photoButton);
photoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
takePhoto(v);
}
});
}
public void takePhoto(View view) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pictures/Pic.jpg");
photo.getParentFile().mkdirs();
new FileOutputStream(photo).close();
imageUri = FileProvider.getUriForFile(Act1.this,
BuildConfig.APPLICATION_ID + ".provider", photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
imageUri);
startActivityForResult(intent, TAKE_PICTURE);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Act1.this, "Uh oh! Looks like we had a problem",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Button postButton;
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.image);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
postButton = (Button) findViewById(R.id.postButton);
postButton.setEnabled(true);
}
}
}
class PostToImgur extends AsyncTask<String, Void, Boolean> {
private Exception exception;
String imageName;
protected Boolean doInBackground(String... files) {
final String upload_to = "https://api.imgur.com/3/upload.json";
final String API_key = "e4d31dbb14e259fa15db0878bb1ae5def4075fb0";
final String clientId = "669c016e544468d";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
httpPost.addHeader("Authorization", "Client-ID " + clientId);
try {
final MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pictures/Pic.jpg");
entity.addPart("image", new FileBody(photo));
entity.addPart("key", new StringBody(API_key));
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost, localContext);
final String response_string = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(response_string);
Log.d("JSON", "received json object:" + json.toString());
if (response.getStatusLine().getStatusCode() == 200 &&
json.getBoolean("success")) {
imageName = "https://imgur.com/" + json.getJSONObject("data").getString("id");
} else {
imageName = "Request failed with status " +
response.getStatusLine().getStatusCode() + " and error " +
json.getString("error");
}
return true;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Act1.this,
"Oops, couldn't upload the image! Make sure you're connected to the internet and try again",
Toast.LENGTH_LONG).show();
Log.d("PostFailure", "failed to do something " + e.toString());
return false;
}
}
protected void onPostExecute(Boolean feed) {
TextView output;
output = (TextView) findViewById(R.id.output);
output.setText(imageName);
}
}
}
|
package com.arcgis.android.samples.search.placesearch;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.MatrixCursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SearchView.OnSuggestionListener;
import android.widget.SimpleCursorAdapter;
import com.esri.android.map.MapView;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.android.toolkit.map.MapViewHelper;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.CallbackListener;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorGeocodeResult;
import com.esri.core.tasks.geocode.LocatorSuggestionParameters;
import com.esri.core.tasks.geocode.LocatorSuggestionResult;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* PlaceSearch app uses the geocoding service to convert addresses to and from
* geographic coordinates and place them on the map. Search for places, addresses,
* etc. and get suggestions as you type.
*
*/
public class MainActivity extends Activity {
private static final String TAG = "PlaceSearch";
private static final String COLUMN_NAME_ADDRESS = "address";
private static final String COLUMN_NAME_X = "x";
private static final String COLUMN_NAME_Y = "y";
private static final String LOCATION_TITLE = "Location";
private static final String SUGGEST_PLACE = "Suggest";
private MapView mMapView;
private String mMapViewState;
// Entry point to ArcGIS for Android Toolkit
private MapViewHelper mMapViewHelper;
private Locator mLocator;
private SearchView mSearchView;
private MenuItem searchMenuItem;
private MatrixCursor mSuggestionCursor;
private static ProgressDialog mProgressDialog;
private LocatorSuggestionParameters suggestParams;
private final Map<String,Point> suggestMap = new TreeMap<>();
private SpatialReference mapSpatialReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup and show progress dialog
mProgressDialog = new ProgressDialog(this) {
@Override
public void onBackPressed() {
// Back key pressed - just dismiss the dialog
mProgressDialog.dismiss();
}
};
// After the content of this activity is set the map can be accessed from the layout
mMapView = (MapView) findViewById(R.id.map);
// Initialize the helper class to use the Toolkit
mMapViewHelper = new MapViewHelper(mMapView);
// Create the default ArcGIS online Locator. If you want to provide your own {@code Locator},
// user other methods of Locator.
mLocator = Locator.createOnlineLocator();
// set logo and enable wrap around
mMapView.setEsriLogoVisible(true);
mMapView.enableWrapAround(true);
mapSpatialReference = mMapView.getSpatialReference();
// Setup listener for map initialized
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
@Override
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
if (mMapViewState == null) {
Log.i(TAG, "MapView.setOnStatusChangedListener() status=" + status.toString());
} else {
mMapView.restoreState(mMapViewState);
}
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_search) {
searchMenuItem = item;
// Create search view and display on the Action Bar
initSearchView();
item.setActionView(mSearchView);
return true;
} else if (id == R.id.action_clear) {
// Remove all the marker graphics
if (mMapViewHelper != null) {
mMapViewHelper.removeAllGraphics();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if ((mSearchView != null) && (!mSearchView.isIconified())) {
// Close the search view when tapping back button
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
invalidateOptionsMenu();
}
} else {
super.onBackPressed();
}
}
// Initialize suggestion cursor
private void initSuggestionCursor() {
String[] cols = new String[]{BaseColumns._ID, COLUMN_NAME_ADDRESS, COLUMN_NAME_X, COLUMN_NAME_Y};
mSuggestionCursor = new MatrixCursor(cols);
}
// Set the suggestion cursor to an Adapter then set it to the search view
private void applySuggestionCursor() {
String[] cols = new String[]{COLUMN_NAME_ADDRESS};
int[] to = new int[]{R.id.suggestion_item_address};
SimpleCursorAdapter mSuggestionAdapter = new SimpleCursorAdapter(mMapView.getContext(), R.layout.suggestion_item, mSuggestionCursor, cols, to, 0);
mSearchView.setSuggestionsAdapter(mSuggestionAdapter);
mSuggestionAdapter.notifyDataSetChanged();
}
// Initialize search view and add event listeners to handle query text changes and suggestion
private void initSearchView() {
if (mMapView == null || !mMapView.isLoaded())
return;
mSearchView = new SearchView(this);
mSearchView.setFocusable(true);
mSearchView.setIconifiedByDefault(false);
mSearchView.setQueryHint(getResources().getString(R.string.search_hint));
mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
getSuggestions(newText);
return true;
}
});
mSearchView.setOnSuggestionListener(new OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
return false;
}
@Override
public boolean onSuggestionClick(int position) {
// Obtain the content of the selected suggesting place via cursor
MatrixCursor cursor = (MatrixCursor) mSearchView.getSuggestionsAdapter().getItem(position);
int indexColumnSuggestion = cursor.getColumnIndex(COLUMN_NAME_ADDRESS);
final String address = cursor.getString(indexColumnSuggestion);
// Find the Location of the suggestion
new FindLocationTask(address).execute(address);
cursor.close();
return true;
}
});
}
//Fetch the Location from the Map and display it
private class FindLocationTask extends AsyncTask<String,Void,Point> {
private Point resultPoint = null;
private String resultAddress;
private Point temp = null;
public FindLocationTask(String address) {
resultAddress = address;
}
@Override
protected Point doInBackground(String... params) {
// get the Location for the suggestion from the map
do {
try {
temp = suggestMap.get(params[0]);
// Project the Location to WGS 84
resultPoint = (Point) GeometryEngine.project(temp, mapSpatialReference, SpatialReference.create(4326));
} catch (Exception e) {
Log.e(TAG,"Error in fetching the Location");
}
} while(temp == null);
return resultPoint;
}
@Override
protected void onPreExecute() {
// Display progress dialog on UI thread
mProgressDialog.setMessage(getString(R.string.address_search));
mProgressDialog.show();
}
@Override
protected void onPostExecute(Point resultPoint) {
// Dismiss progress dialog
mProgressDialog.dismiss();
if (resultPoint == null)
return;
// Display the result
displaySearchResult(resultPoint.getX(),resultPoint.getY(),resultAddress);
hideKeyboard();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
mMapViewState = mMapView.retainState();
mMapView.pause();
}
@Override
protected void onResume() {
super.onResume();
// Start the MapView running again
if (mMapView != null) {
mMapView.unpause();
if (mMapViewState != null) {
mMapView.restoreState(mMapViewState);
}
}
}
/**
* Provide character-by-character suggestions for the search string
*
* @param suggestText String the user typed so far to fetch the suggestions
*/
protected void getSuggestions(String suggestText) {
final CallbackListener<List<LocatorSuggestionResult>> suggestCallback = new CallbackListener<List<LocatorSuggestionResult>>() {
@Override
public void onCallback(List<LocatorSuggestionResult> locatorSuggestionResults) {
final List<LocatorSuggestionResult> locSuggestionResults = locatorSuggestionResults;
if (locatorSuggestionResults == null)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
int key = 0;
if(locSuggestionResults.size() > 0) {
// Add suggestion list to a cursor
initSuggestionCursor();
for (final LocatorSuggestionResult result : locSuggestionResults) {
// In the background, save the Suggestion and it's location in a Map
new Thread(new Runnable() {
@Override
public void run() {
List<LocatorGeocodeResult> locatorGeocodeResults;
try {
locatorGeocodeResults = mLocator.find(result, 2, null, mapSpatialReference);
LocatorGeocodeResult suggestionResult = locatorGeocodeResults.get(0);
suggestMap.put(result.getText(), suggestionResult.getLocation());
} catch (Exception e) {
Log.e(TAG,"Exception in FIND");
Log.e(TAG,e.getMessage());
}
}
}).start();
// Add the suggestion results to the cursor
mSuggestionCursor.addRow(new Object[]{key++, result.getText(), "0", "0"});
}
applySuggestionCursor();
}
}
});
}
@Override
public void onError(Throwable throwable) {
//Log the error
Log.e(MainActivity.class.getSimpleName(), "No Results found!!");
Log.e(MainActivity.class.getSimpleName(), throwable.getMessage());
}
};
try {
// Initialize the LocatorSuggestion parameters
locatorParams(SUGGEST_PLACE,suggestText);
mLocator.suggest(suggestParams, suggestCallback);
} catch (Exception e) {
Log.e(MainActivity.class.getSimpleName(),"No Results found");
Log.e(MainActivity.class.getSimpleName(),e.getMessage());
}
}
/**
* Initialize the LocatorSuggestionParameters or LocatorFindParameters
*
* @param type A String determining the type of parameters to be initialized
* @param query The string for which the locator parameters are to be initialized
*/
protected void locatorParams(String type, String query) {
if(type.contentEquals(SUGGEST_PLACE)) {
suggestParams = new LocatorSuggestionParameters(query);
// Use the centre of the current map extent as the find location point
suggestParams.setLocation(mMapView.getCenter(), mMapView.getSpatialReference());
// Set the radial search distance in meters
suggestParams.setDistance(500.0);
}
}
/**
* Display the search location on the map
* @param x Longitude of the place
* @param y Latitude of the place
* @param address The address of the location
*/
protected void displaySearchResult(double x, double y, String address) {
// Add a marker at the found place. When tapping on the marker, a Callout with the address
// will be displayed
mMapViewHelper.addMarkerGraphic(y, x, LOCATION_TITLE, address, android.R.drawable.ic_menu_myplaces, null, false, 1);
mMapView.centerAndZoom(y, x, 14);
mSearchView.setQuery(address, true);
}
protected void hideKeyboard() {
// Hide soft keyboard
mSearchView.clearFocus();
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
}
}
|
package com.facebook.react.views.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import androidx.annotation.Nullable;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.uimanager.FloatUtil;
import com.facebook.react.uimanager.Spacing;
import com.facebook.yoga.YogaConstants;
import java.util.Arrays;
import java.util.Locale;
/**
* A subclass of {@link Drawable} used for background of {@link ReactViewGroup}. It supports drawing
* background color and borders (including rounded borders) by providing a react friendly API
* (setter for each of those properties).
*
* <p>The implementation tries to allocate as few objects as possible depending on which properties
* are set. E.g. for views with rounded background/borders we allocate {@code
* mInnerClipPathForBorderRadius} and {@code mInnerClipTempRectForBorderRadius}. In case when view
* have a rectangular borders we allocate {@code mBorderWidthResult} and similar. When only
* background color is set we won't allocate any extra/unnecessary objects.
*/
public class ReactViewBackgroundDrawable extends Drawable {
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final int DEFAULT_BORDER_RGB = 0x00FFFFFF & DEFAULT_BORDER_COLOR;
private static final int DEFAULT_BORDER_ALPHA = (0xFF000000 & DEFAULT_BORDER_COLOR) >>> 24;
// ~0 == 0xFFFFFFFF, all bits set to 1.
private static final int ALL_BITS_SET = ~0;
// 0 == 0x00000000, all bits set to 0.
private static final int ALL_BITS_UNSET = 0;
private enum BorderStyle {
SOLID,
DASHED,
DOTTED;
public static @Nullable PathEffect getPathEffect(BorderStyle style, float borderWidth) {
switch (style) {
case SOLID:
return null;
case DASHED:
return new DashPathEffect(
new float[] {borderWidth * 3, borderWidth * 3, borderWidth * 3, borderWidth * 3}, 0);
case DOTTED:
return new DashPathEffect(
new float[] {borderWidth, borderWidth, borderWidth, borderWidth}, 0);
default:
return null;
}
}
};
/* Value at Spacing.ALL index used for rounded borders, whole array used by rectangular borders */
private @Nullable Spacing mBorderWidth;
private @Nullable Spacing mBorderRGB;
private @Nullable Spacing mBorderAlpha;
private @Nullable BorderStyle mBorderStyle;
/* Used for rounded border and rounded background */
private @Nullable PathEffect mPathEffectForBorderStyle;
private @Nullable Path mInnerClipPathForBorderRadius;
private @Nullable Path mOuterClipPathForBorderRadius;
private @Nullable Path mPathForBorderRadiusOutline;
private @Nullable Path mPathForBorder;
private @Nullable Path mCenterDrawPath;
private @Nullable RectF mInnerClipTempRectForBorderRadius;
private @Nullable RectF mOuterClipTempRectForBorderRadius;
private @Nullable RectF mTempRectForBorderRadiusOutline;
private @Nullable RectF mTempRectForCenterDrawPath;
private @Nullable PointF mInnerTopLeftCorner;
private @Nullable PointF mInnerTopRightCorner;
private @Nullable PointF mInnerBottomRightCorner;
private @Nullable PointF mInnerBottomLeftCorner;
private boolean mNeedUpdatePathForBorderRadius = false;
private float mBorderRadius = YogaConstants.UNDEFINED;
/* Used by all types of background and for drawing borders */
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int mColor = Color.TRANSPARENT;
private int mAlpha = 255;
private @Nullable float[] mBorderCornerRadii;
private final Context mContext;
private int mLayoutDirection;
public enum BorderRadiusLocation {
TOP_LEFT,
TOP_RIGHT,
BOTTOM_RIGHT,
BOTTOM_LEFT,
TOP_START,
TOP_END,
BOTTOM_START,
BOTTOM_END
}
public ReactViewBackgroundDrawable(Context context) {
mContext = context;
}
@Override
public void draw(Canvas canvas) {
updatePathEffect();
if (!hasRoundedBorders()) {
drawRectangularBackgroundWithBorders(canvas);
} else {
drawRoundedBackgroundWithBorders(canvas);
}
}
public boolean hasRoundedBorders() {
if (!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) {
return true;
}
if (mBorderCornerRadii != null) {
for (final float borderRadii : mBorderCornerRadii) {
if (!YogaConstants.isUndefined(borderRadii) && borderRadii > 0) {
return true;
}
}
}
return false;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mNeedUpdatePathForBorderRadius = true;
}
@Override
public void setAlpha(int alpha) {
if (alpha != mAlpha) {
mAlpha = alpha;
invalidateSelf();
}
}
@Override
public int getAlpha() {
return mAlpha;
}
@Override
public void setColorFilter(ColorFilter cf) {
// do nothing
}
@Override
public int getOpacity() {
return ColorUtil.getOpacityFromColor(ColorUtil.multiplyColorAlpha(mColor, mAlpha));
}
/* Android's elevation implementation requires this to be implemented to know where to draw the shadow. */
@Override
public void getOutline(Outline outline) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
super.getOutline(outline);
return;
}
if ((!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0)
|| mBorderCornerRadii != null) {
updatePath();
outline.setConvexPath(mPathForBorderRadiusOutline);
} else {
outline.setRect(getBounds());
}
}
public void setBorderWidth(int position, float width) {
if (mBorderWidth == null) {
mBorderWidth = new Spacing();
}
if (!FloatUtil.floatsEqual(mBorderWidth.getRaw(position), width)) {
mBorderWidth.set(position, width);
switch (position) {
case Spacing.ALL:
case Spacing.LEFT:
case Spacing.BOTTOM:
case Spacing.RIGHT:
case Spacing.TOP:
case Spacing.START:
case Spacing.END:
mNeedUpdatePathForBorderRadius = true;
}
invalidateSelf();
}
}
public void setBorderColor(int position, float rgb, float alpha) {
this.setBorderRGB(position, rgb);
this.setBorderAlpha(position, alpha);
}
private void setBorderRGB(int position, float rgb) {
// set RGB component
if (mBorderRGB == null) {
mBorderRGB = new Spacing(DEFAULT_BORDER_RGB);
}
if (!FloatUtil.floatsEqual(mBorderRGB.getRaw(position), rgb)) {
mBorderRGB.set(position, rgb);
invalidateSelf();
}
}
private void setBorderAlpha(int position, float alpha) {
// set Alpha component
if (mBorderAlpha == null) {
mBorderAlpha = new Spacing(DEFAULT_BORDER_ALPHA);
}
if (!FloatUtil.floatsEqual(mBorderAlpha.getRaw(position), alpha)) {
mBorderAlpha.set(position, alpha);
invalidateSelf();
}
}
public void setBorderStyle(@Nullable String style) {
BorderStyle borderStyle =
style == null ? null : BorderStyle.valueOf(style.toUpperCase(Locale.US));
if (mBorderStyle != borderStyle) {
mBorderStyle = borderStyle;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public void setRadius(float radius) {
if (!FloatUtil.floatsEqual(mBorderRadius, radius)) {
mBorderRadius = radius;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public void setRadius(float radius, int position) {
if (mBorderCornerRadii == null) {
mBorderCornerRadii = new float[8];
Arrays.fill(mBorderCornerRadii, YogaConstants.UNDEFINED);
}
if (!FloatUtil.floatsEqual(mBorderCornerRadii[position], radius)) {
mBorderCornerRadii[position] = radius;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public float getFullBorderRadius() {
return YogaConstants.isUndefined(mBorderRadius) ? 0 : mBorderRadius;
}
public float getBorderRadius(final BorderRadiusLocation location) {
return getBorderRadiusOrDefaultTo(YogaConstants.UNDEFINED, location);
}
public float getBorderRadiusOrDefaultTo(
final float defaultValue, final BorderRadiusLocation location) {
if (mBorderCornerRadii == null) {
return defaultValue;
}
final float radius = mBorderCornerRadii[location.ordinal()];
if (YogaConstants.isUndefined(radius)) {
return defaultValue;
}
return radius;
}
public void setColor(int color) {
mColor = color;
invalidateSelf();
}
/** Similar to Drawable.getLayoutDirection, but available in APIs < 23. */
public int getResolvedLayoutDirection() {
return mLayoutDirection;
}
/** Similar to Drawable.setLayoutDirection, but available in APIs < 23. */
public boolean setResolvedLayoutDirection(int layoutDirection) {
if (mLayoutDirection != layoutDirection) {
mLayoutDirection = layoutDirection;
return onResolvedLayoutDirectionChanged(layoutDirection);
}
return false;
}
/** Similar to Drawable.onLayoutDirectionChanged, but available in APIs < 23. */
public boolean onResolvedLayoutDirectionChanged(int layoutDirection) {
return false;
}
@VisibleForTesting
public int getColor() {
return mColor;
}
private void drawRoundedBackgroundWithBorders(Canvas canvas) {
updatePath();
canvas.save();
int useColor = ColorUtil.multiplyColorAlpha(mColor, mAlpha);
if (Color.alpha(useColor) != 0) { // color is not transparent
mPaint.setColor(useColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawPath(mInnerClipPathForBorderRadius, mPaint);
}
final RectF borderWidth = getDirectionAwareBorderInsets();
int colorLeft = getBorderColor(Spacing.LEFT);
int colorTop = getBorderColor(Spacing.TOP);
int colorRight = getBorderColor(Spacing.RIGHT);
int colorBottom = getBorderColor(Spacing.BOTTOM);
if (borderWidth.top > 0
|| borderWidth.bottom > 0
|| borderWidth.left > 0
|| borderWidth.right > 0) {
// If it's a full and even border draw inner rect path with stroke
final float fullBorderWidth = getFullBorderWidth();
int borderColor = getBorderColor(Spacing.ALL);
if (borderWidth.top == fullBorderWidth
&& borderWidth.bottom == fullBorderWidth
&& borderWidth.left == fullBorderWidth
&& borderWidth.right == fullBorderWidth
&& colorLeft == borderColor
&& colorTop == borderColor
&& colorRight == borderColor
&& colorBottom == borderColor) {
if (fullBorderWidth > 0) {
mPaint.setColor(ColorUtil.multiplyColorAlpha(borderColor, mAlpha));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(fullBorderWidth);
canvas.drawPath(mCenterDrawPath, mPaint);
}
}
// In the case of uneven border widths/colors draw quadrilateral in each direction
else {
mPaint.setStyle(Paint.Style.FILL);
// Draw border
canvas.clipPath(mOuterClipPathForBorderRadius, Region.Op.INTERSECT);
canvas.clipPath(mInnerClipPathForBorderRadius, Region.Op.DIFFERENCE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
int colorStart = getBorderColor(Spacing.START);
int colorEnd = getBorderColor(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (!isBorderColorDefined(Spacing.START)) {
colorStart = colorLeft;
}
if (!isBorderColorDefined(Spacing.END)) {
colorEnd = colorRight;
}
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
colorLeft = directionAwareColorLeft;
colorRight = directionAwareColorRight;
} else {
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
final boolean isColorStartDefined = isBorderColorDefined(Spacing.START);
final boolean isColorEndDefined = isBorderColorDefined(Spacing.END);
final boolean isDirectionAwareColorLeftDefined =
isRTL ? isColorEndDefined : isColorStartDefined;
final boolean isDirectionAwareColorRightDefined =
isRTL ? isColorStartDefined : isColorEndDefined;
if (isDirectionAwareColorLeftDefined) {
colorLeft = directionAwareColorLeft;
}
if (isDirectionAwareColorRightDefined) {
colorRight = directionAwareColorRight;
}
}
}
final float left = mOuterClipTempRectForBorderRadius.left;
final float right = mOuterClipTempRectForBorderRadius.right;
final float top = mOuterClipTempRectForBorderRadius.top;
final float bottom = mOuterClipTempRectForBorderRadius.bottom;
if (borderWidth.left > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = mInnerTopLeftCorner.x;
final float y2 = mInnerTopLeftCorner.y;
final float x3 = mInnerBottomLeftCorner.x;
final float y3 = mInnerBottomLeftCorner.y;
final float x4 = left;
final float y4 = bottom;
drawQuadrilateral(canvas, colorLeft, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.top > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = mInnerTopLeftCorner.x;
final float y2 = mInnerTopLeftCorner.y;
final float x3 = mInnerTopRightCorner.x;
final float y3 = mInnerTopRightCorner.y;
final float x4 = right;
final float y4 = top;
drawQuadrilateral(canvas, colorTop, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.right > 0) {
final float x1 = right;
final float y1 = top;
final float x2 = mInnerTopRightCorner.x;
final float y2 = mInnerTopRightCorner.y;
final float x3 = mInnerBottomRightCorner.x;
final float y3 = mInnerBottomRightCorner.y;
final float x4 = right;
final float y4 = bottom;
drawQuadrilateral(canvas, colorRight, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.bottom > 0) {
final float x1 = left;
final float y1 = bottom;
final float x2 = mInnerBottomLeftCorner.x;
final float y2 = mInnerBottomLeftCorner.y;
final float x3 = mInnerBottomRightCorner.x;
final float y3 = mInnerBottomRightCorner.y;
final float x4 = right;
final float y4 = bottom;
drawQuadrilateral(canvas, colorBottom, x1, y1, x2, y2, x3, y3, x4, y4);
}
}
}
canvas.restore();
}
private void updatePath() {
if (!mNeedUpdatePathForBorderRadius) {
return;
}
mNeedUpdatePathForBorderRadius = false;
if (mInnerClipPathForBorderRadius == null) {
mInnerClipPathForBorderRadius = new Path();
}
if (mOuterClipPathForBorderRadius == null) {
mOuterClipPathForBorderRadius = new Path();
}
if (mPathForBorderRadiusOutline == null) {
mPathForBorderRadiusOutline = new Path();
}
if (mCenterDrawPath == null) {
mCenterDrawPath = new Path();
}
if (mInnerClipTempRectForBorderRadius == null) {
mInnerClipTempRectForBorderRadius = new RectF();
}
if (mOuterClipTempRectForBorderRadius == null) {
mOuterClipTempRectForBorderRadius = new RectF();
}
if (mTempRectForBorderRadiusOutline == null) {
mTempRectForBorderRadiusOutline = new RectF();
}
if (mTempRectForCenterDrawPath == null) {
mTempRectForCenterDrawPath = new RectF();
}
mInnerClipPathForBorderRadius.reset();
mOuterClipPathForBorderRadius.reset();
mPathForBorderRadiusOutline.reset();
mCenterDrawPath.reset();
mInnerClipTempRectForBorderRadius.set(getBounds());
mOuterClipTempRectForBorderRadius.set(getBounds());
mTempRectForBorderRadiusOutline.set(getBounds());
mTempRectForCenterDrawPath.set(getBounds());
final RectF borderWidth = getDirectionAwareBorderInsets();
mInnerClipTempRectForBorderRadius.top += borderWidth.top;
mInnerClipTempRectForBorderRadius.bottom -= borderWidth.bottom;
mInnerClipTempRectForBorderRadius.left += borderWidth.left;
mInnerClipTempRectForBorderRadius.right -= borderWidth.right;
mTempRectForCenterDrawPath.top += borderWidth.top * 0.5f;
mTempRectForCenterDrawPath.bottom -= borderWidth.bottom * 0.5f;
mTempRectForCenterDrawPath.left += borderWidth.left * 0.5f;
mTempRectForCenterDrawPath.right -= borderWidth.right * 0.5f;
final float borderRadius = getFullBorderRadius();
float topLeftRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_LEFT);
float topRightRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_RIGHT);
float bottomLeftRadius =
getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_LEFT);
float bottomRightRadius =
getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_RIGHT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
float topStartRadius = getBorderRadius(BorderRadiusLocation.TOP_START);
float topEndRadius = getBorderRadius(BorderRadiusLocation.TOP_END);
float bottomStartRadius = getBorderRadius(BorderRadiusLocation.BOTTOM_START);
float bottomEndRadius = getBorderRadius(BorderRadiusLocation.BOTTOM_END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (YogaConstants.isUndefined(topStartRadius)) {
topStartRadius = topLeftRadius;
}
if (YogaConstants.isUndefined(topEndRadius)) {
topEndRadius = topRightRadius;
}
if (YogaConstants.isUndefined(bottomStartRadius)) {
bottomStartRadius = bottomLeftRadius;
}
if (YogaConstants.isUndefined(bottomEndRadius)) {
bottomEndRadius = bottomRightRadius;
}
final float directionAwareTopLeftRadius = isRTL ? topEndRadius : topStartRadius;
final float directionAwareTopRightRadius = isRTL ? topStartRadius : topEndRadius;
final float directionAwareBottomLeftRadius = isRTL ? bottomEndRadius : bottomStartRadius;
final float directionAwareBottomRightRadius = isRTL ? bottomStartRadius : bottomEndRadius;
topLeftRadius = directionAwareTopLeftRadius;
topRightRadius = directionAwareTopRightRadius;
bottomLeftRadius = directionAwareBottomLeftRadius;
bottomRightRadius = directionAwareBottomRightRadius;
} else {
final float directionAwareTopLeftRadius = isRTL ? topEndRadius : topStartRadius;
final float directionAwareTopRightRadius = isRTL ? topStartRadius : topEndRadius;
final float directionAwareBottomLeftRadius = isRTL ? bottomEndRadius : bottomStartRadius;
final float directionAwareBottomRightRadius = isRTL ? bottomStartRadius : bottomEndRadius;
if (!YogaConstants.isUndefined(directionAwareTopLeftRadius)) {
topLeftRadius = directionAwareTopLeftRadius;
}
if (!YogaConstants.isUndefined(directionAwareTopRightRadius)) {
topRightRadius = directionAwareTopRightRadius;
}
if (!YogaConstants.isUndefined(directionAwareBottomLeftRadius)) {
bottomLeftRadius = directionAwareBottomLeftRadius;
}
if (!YogaConstants.isUndefined(directionAwareBottomRightRadius)) {
bottomRightRadius = directionAwareBottomRightRadius;
}
}
}
final float innerTopLeftRadiusX = Math.max(topLeftRadius - borderWidth.left, 0);
final float innerTopLeftRadiusY = Math.max(topLeftRadius - borderWidth.top, 0);
final float innerTopRightRadiusX = Math.max(topRightRadius - borderWidth.right, 0);
final float innerTopRightRadiusY = Math.max(topRightRadius - borderWidth.top, 0);
final float innerBottomRightRadiusX = Math.max(bottomRightRadius - borderWidth.right, 0);
final float innerBottomRightRadiusY = Math.max(bottomRightRadius - borderWidth.bottom, 0);
final float innerBottomLeftRadiusX = Math.max(bottomLeftRadius - borderWidth.left, 0);
final float innerBottomLeftRadiusY = Math.max(bottomLeftRadius - borderWidth.bottom, 0);
mInnerClipPathForBorderRadius.addRoundRect(
mInnerClipTempRectForBorderRadius,
new float[] {
innerTopLeftRadiusX,
innerTopLeftRadiusY,
innerTopRightRadiusX,
innerTopRightRadiusY,
innerBottomRightRadiusX,
innerBottomRightRadiusY,
innerBottomLeftRadiusX,
innerBottomLeftRadiusY,
},
Path.Direction.CW);
mOuterClipPathForBorderRadius.addRoundRect(
mOuterClipTempRectForBorderRadius,
new float[] {
topLeftRadius,
topLeftRadius,
topRightRadius,
topRightRadius,
bottomRightRadius,
bottomRightRadius,
bottomLeftRadius,
bottomLeftRadius
},
Path.Direction.CW);
float extraRadiusForOutline = 0;
if (mBorderWidth != null) {
extraRadiusForOutline = mBorderWidth.get(Spacing.ALL) / 2f;
}
mPathForBorderRadiusOutline.addRoundRect(
mTempRectForBorderRadiusOutline,
new float[] {
topLeftRadius + extraRadiusForOutline,
topLeftRadius + extraRadiusForOutline,
topRightRadius + extraRadiusForOutline,
topRightRadius + extraRadiusForOutline,
bottomRightRadius + extraRadiusForOutline,
bottomRightRadius + extraRadiusForOutline,
bottomLeftRadius + extraRadiusForOutline,
bottomLeftRadius + extraRadiusForOutline
},
Path.Direction.CW);
mCenterDrawPath.addRoundRect(
mTempRectForCenterDrawPath,
new float[] {
Math.max(
topLeftRadius - borderWidth.left * 0.5f,
(borderWidth.left > 0.0f) ? (topLeftRadius / borderWidth.left) : 0.0f),
Math.max(
topLeftRadius - borderWidth.top * 0.5f,
(borderWidth.top > 0.0f) ? (topLeftRadius / borderWidth.top) : 0.0f),
Math.max(
topRightRadius - borderWidth.right * 0.5f,
(borderWidth.right > 0.0f) ? (topRightRadius / borderWidth.right) : 0.0f),
Math.max(
topRightRadius - borderWidth.top * 0.5f,
(borderWidth.top > 0.0f) ? (topRightRadius / borderWidth.top) : 0.0f),
Math.max(
bottomRightRadius - borderWidth.right * 0.5f,
(borderWidth.right > 0.0f) ? (bottomRightRadius / borderWidth.right) : 0.0f),
Math.max(
bottomRightRadius - borderWidth.bottom * 0.5f,
(borderWidth.bottom > 0.0f) ? (bottomRightRadius / borderWidth.bottom) : 0.0f),
Math.max(
bottomLeftRadius - borderWidth.left * 0.5f,
(borderWidth.left > 0.0f) ? (bottomLeftRadius / borderWidth.left) : 0.0f),
Math.max(
bottomLeftRadius - borderWidth.bottom * 0.5f,
(borderWidth.bottom > 0.0f) ? (bottomLeftRadius / borderWidth.bottom) : 0.0f)
},
Path.Direction.CW);
if (mInnerTopLeftCorner == null) {
mInnerTopLeftCorner = new PointF();
}
/** Compute mInnerTopLeftCorner */
mInnerTopLeftCorner.x = mInnerClipTempRectForBorderRadius.left;
mInnerTopLeftCorner.y = mInnerClipTempRectForBorderRadius.top;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.top,
mInnerClipTempRectForBorderRadius.left + 2 * innerTopLeftRadiusX,
mInnerClipTempRectForBorderRadius.top + 2 * innerTopLeftRadiusY,
// Line Start
mOuterClipTempRectForBorderRadius.left,
mOuterClipTempRectForBorderRadius.top,
// Line End
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.top,
// Result
mInnerTopLeftCorner);
/** Compute mInnerBottomLeftCorner */
if (mInnerBottomLeftCorner == null) {
mInnerBottomLeftCorner = new PointF();
}
mInnerBottomLeftCorner.x = mInnerClipTempRectForBorderRadius.left;
mInnerBottomLeftCorner.y = mInnerClipTempRectForBorderRadius.bottom;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.bottom - 2 * innerBottomLeftRadiusY,
mInnerClipTempRectForBorderRadius.left + 2 * innerBottomLeftRadiusX,
mInnerClipTempRectForBorderRadius.bottom,
// Line Start
mOuterClipTempRectForBorderRadius.left,
mOuterClipTempRectForBorderRadius.bottom,
// Line End
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.bottom,
// Result
mInnerBottomLeftCorner);
/** Compute mInnerTopRightCorner */
if (mInnerTopRightCorner == null) {
mInnerTopRightCorner = new PointF();
}
mInnerTopRightCorner.x = mInnerClipTempRectForBorderRadius.right;
mInnerTopRightCorner.y = mInnerClipTempRectForBorderRadius.top;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.right - 2 * innerTopRightRadiusX,
mInnerClipTempRectForBorderRadius.top,
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.top + 2 * innerTopRightRadiusY,
// Line Start
mOuterClipTempRectForBorderRadius.right,
mOuterClipTempRectForBorderRadius.top,
// Line End
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.top,
// Result
mInnerTopRightCorner);
/** Compute mInnerBottomRightCorner */
if (mInnerBottomRightCorner == null) {
mInnerBottomRightCorner = new PointF();
}
mInnerBottomRightCorner.x = mInnerClipTempRectForBorderRadius.right;
mInnerBottomRightCorner.y = mInnerClipTempRectForBorderRadius.bottom;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.right - 2 * innerBottomRightRadiusX,
mInnerClipTempRectForBorderRadius.bottom - 2 * innerBottomRightRadiusY,
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.bottom,
// Line Start
mOuterClipTempRectForBorderRadius.right,
mOuterClipTempRectForBorderRadius.bottom,
// Line End
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.bottom,
// Result
mInnerBottomRightCorner);
}
private static void getEllipseIntersectionWithLine(
double ellipseBoundsLeft,
double ellipseBoundsTop,
double ellipseBoundsRight,
double ellipseBoundsBottom,
double lineStartX,
double lineStartY,
double lineEndX,
double lineEndY,
PointF result) {
final double ellipseCenterX = (ellipseBoundsLeft + ellipseBoundsRight) / 2;
final double ellipseCenterY = (ellipseBoundsTop + ellipseBoundsBottom) / 2;
/**
* Step 1:
*
* <p>Translate the line so that the ellipse is at the origin.
*
* <p>Why? It makes the math easier by changing the ellipse equation from ((x -
* ellipseCenterX)/a)^2 + ((y - ellipseCenterY)/b)^2 = 1 to (x/a)^2 + (y/b)^2 = 1.
*/
lineStartX -= ellipseCenterX;
lineStartY -= ellipseCenterY;
lineEndX -= ellipseCenterX;
lineEndY -= ellipseCenterY;
/**
* Step 2:
*
* <p>Ellipse equation: (x/a)^2 + (y/b)^2 = 1 Line equation: y = mx + c
*/
final double a = Math.abs(ellipseBoundsRight - ellipseBoundsLeft) / 2;
final double b = Math.abs(ellipseBoundsBottom - ellipseBoundsTop) / 2;
final double m = (lineEndY - lineStartY) / (lineEndX - lineStartX);
final double c = lineStartY - m * lineStartX; // Just a point on the line
/**
* Step 3:
*
* <p>Substitute the Line equation into the Ellipse equation. Solve for x. Eventually, you'll
* have to use the quadratic formula.
*
* <p>Quadratic formula: Ax^2 + Bx + C = 0
*/
final double A = (b * b + a * a * m * m);
final double B = 2 * a * a * c * m;
final double C = (a * a * (c * c - b * b));
/**
* Step 4:
*
* <p>Apply Quadratic formula. D = determinant / 2A
*/
final double D = Math.sqrt(-C / A + Math.pow(B / (2 * A), 2));
final double x2 = -B / (2 * A) - D;
final double y2 = m * x2 + c;
/**
* Step 5:
*
* <p>Undo the space transformation in Step 5.
*/
final double x = x2 + ellipseCenterX;
final double y = y2 + ellipseCenterY;
if (!Double.isNaN(x) && !Double.isNaN(y)) {
result.x = (float) x;
result.y = (float) y;
}
}
public float getBorderWidthOrDefaultTo(final float defaultValue, final int spacingType) {
if (mBorderWidth == null) {
return defaultValue;
}
final float width = mBorderWidth.getRaw(spacingType);
if (YogaConstants.isUndefined(width)) {
return defaultValue;
}
return width;
}
/** Set type of border */
private void updatePathEffect() {
mPathEffectForBorderStyle =
mBorderStyle != null ? BorderStyle.getPathEffect(mBorderStyle, getFullBorderWidth()) : null;
mPaint.setPathEffect(mPathEffectForBorderStyle);
}
/** For rounded borders we use default "borderWidth" property. */
public float getFullBorderWidth() {
return (mBorderWidth != null && !YogaConstants.isUndefined(mBorderWidth.getRaw(Spacing.ALL)))
? mBorderWidth.getRaw(Spacing.ALL)
: 0f;
}
/**
* Quickly determine if all the set border colors are equal. Bitwise AND all the set colors
* together, then OR them all together. If the AND and the OR are the same, then the colors are
* compatible, so return this color.
*
* <p>Used to avoid expensive path creation and expensive calls to canvas.drawPath
*
* @return A compatible border color, or zero if the border colors are not compatible.
*/
private static int fastBorderCompatibleColorOrZero(
int borderLeft,
int borderTop,
int borderRight,
int borderBottom,
int colorLeft,
int colorTop,
int colorRight,
int colorBottom) {
int andSmear =
(borderLeft > 0 ? colorLeft : ALL_BITS_SET)
& (borderTop > 0 ? colorTop : ALL_BITS_SET)
& (borderRight > 0 ? colorRight : ALL_BITS_SET)
& (borderBottom > 0 ? colorBottom : ALL_BITS_SET);
int orSmear =
(borderLeft > 0 ? colorLeft : ALL_BITS_UNSET)
| (borderTop > 0 ? colorTop : ALL_BITS_UNSET)
| (borderRight > 0 ? colorRight : ALL_BITS_UNSET)
| (borderBottom > 0 ? colorBottom : ALL_BITS_UNSET);
return andSmear == orSmear ? andSmear : 0;
}
private void drawRectangularBackgroundWithBorders(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
int useColor = ColorUtil.multiplyColorAlpha(mColor, mAlpha);
if (Color.alpha(useColor) != 0) { // color is not transparent
mPaint.setColor(useColor);
canvas.drawRect(getBounds(), mPaint);
}
final RectF borderWidth = getDirectionAwareBorderInsets();
final int borderLeft = Math.round(borderWidth.left);
final int borderTop = Math.round(borderWidth.top);
final int borderRight = Math.round(borderWidth.right);
final int borderBottom = Math.round(borderWidth.bottom);
// maybe draw borders?
if (borderLeft > 0 || borderRight > 0 || borderTop > 0 || borderBottom > 0) {
Rect bounds = getBounds();
int colorLeft = getBorderColor(Spacing.LEFT);
int colorTop = getBorderColor(Spacing.TOP);
int colorRight = getBorderColor(Spacing.RIGHT);
int colorBottom = getBorderColor(Spacing.BOTTOM);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
int colorStart = getBorderColor(Spacing.START);
int colorEnd = getBorderColor(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (!isBorderColorDefined(Spacing.START)) {
colorStart = colorLeft;
}
if (!isBorderColorDefined(Spacing.END)) {
colorEnd = colorRight;
}
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
colorLeft = directionAwareColorLeft;
colorRight = directionAwareColorRight;
} else {
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
final boolean isColorStartDefined = isBorderColorDefined(Spacing.START);
final boolean isColorEndDefined = isBorderColorDefined(Spacing.END);
final boolean isDirectionAwareColorLeftDefined =
isRTL ? isColorEndDefined : isColorStartDefined;
final boolean isDirectionAwareColorRightDefined =
isRTL ? isColorStartDefined : isColorEndDefined;
if (isDirectionAwareColorLeftDefined) {
colorLeft = directionAwareColorLeft;
}
if (isDirectionAwareColorRightDefined) {
colorRight = directionAwareColorRight;
}
}
}
int left = bounds.left;
int top = bounds.top;
// Check for fast path to border drawing.
int fastBorderColor =
fastBorderCompatibleColorOrZero(
borderLeft,
borderTop,
borderRight,
borderBottom,
colorLeft,
colorTop,
colorRight,
colorBottom);
if (fastBorderColor != 0) {
if (Color.alpha(fastBorderColor) != 0) {
// Border color is not transparent.
int right = bounds.right;
int bottom = bounds.bottom;
mPaint.setColor(fastBorderColor);
if (borderLeft > 0) {
int leftInset = left + borderLeft;
canvas.drawRect(left, top, leftInset, bottom - borderBottom, mPaint);
}
if (borderTop > 0) {
int topInset = top + borderTop;
canvas.drawRect(left + borderLeft, top, right, topInset, mPaint);
}
if (borderRight > 0) {
int rightInset = right - borderRight;
canvas.drawRect(rightInset, top + borderTop, right, bottom, mPaint);
}
if (borderBottom > 0) {
int bottomInset = bottom - borderBottom;
canvas.drawRect(left, bottomInset, right - borderRight, bottom, mPaint);
}
}
} else {
// If the path drawn previously is of the same color,
// there would be a slight white space between borders
// with anti-alias set to true.
// Therefore we need to disable anti-alias, and
// after drawing is done, we will re-enable it.
mPaint.setAntiAlias(false);
int width = bounds.width();
int height = bounds.height();
if (borderLeft > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = left + borderLeft;
final float y2 = top + borderTop;
final float x3 = left + borderLeft;
final float y3 = top + height - borderBottom;
final float x4 = left;
final float y4 = top + height;
drawQuadrilateral(canvas, colorLeft, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderTop > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = left + borderLeft;
final float y2 = top + borderTop;
final float x3 = left + width - borderRight;
final float y3 = top + borderTop;
final float x4 = left + width;
final float y4 = top;
drawQuadrilateral(canvas, colorTop, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderRight > 0) {
final float x1 = left + width;
final float y1 = top;
final float x2 = left + width;
final float y2 = top + height;
final float x3 = left + width - borderRight;
final float y3 = top + height - borderBottom;
final float x4 = left + width - borderRight;
final float y4 = top + borderTop;
drawQuadrilateral(canvas, colorRight, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderBottom > 0) {
final float x1 = left;
final float y1 = top + height;
final float x2 = left + width;
final float y2 = top + height;
final float x3 = left + width - borderRight;
final float y3 = top + height - borderBottom;
final float x4 = left + borderLeft;
final float y4 = top + height - borderBottom;
drawQuadrilateral(canvas, colorBottom, x1, y1, x2, y2, x3, y3, x4, y4);
}
// re-enable anti alias
mPaint.setAntiAlias(true);
}
}
}
private void drawQuadrilateral(
Canvas canvas,
int fillColor,
float x1,
float y1,
float x2,
float y2,
float x3,
float y3,
float x4,
float y4) {
if (fillColor == Color.TRANSPARENT) {
return;
}
if (mPathForBorder == null) {
mPathForBorder = new Path();
}
mPaint.setColor(fillColor);
mPathForBorder.reset();
mPathForBorder.moveTo(x1, y1);
mPathForBorder.lineTo(x2, y2);
mPathForBorder.lineTo(x3, y3);
mPathForBorder.lineTo(x4, y4);
mPathForBorder.lineTo(x1, y1);
canvas.drawPath(mPathForBorder, mPaint);
}
private int getBorderWidth(int position) {
if (mBorderWidth == null) {
return 0;
}
final float width = mBorderWidth.get(position);
return YogaConstants.isUndefined(width) ? -1 : Math.round(width);
}
private static int colorFromAlphaAndRGBComponents(float alpha, float rgb) {
int rgbComponent = 0x00FFFFFF & (int) rgb;
int alphaComponent = 0xFF000000 & ((int) alpha) << 24;
return rgbComponent | alphaComponent;
}
private boolean isBorderColorDefined(int position) {
final float rgb = mBorderRGB != null ? mBorderRGB.get(position) : YogaConstants.UNDEFINED;
final float alpha = mBorderAlpha != null ? mBorderAlpha.get(position) : YogaConstants.UNDEFINED;
return !YogaConstants.isUndefined(rgb) && !YogaConstants.isUndefined(alpha);
}
private int getBorderColor(int position) {
float rgb = mBorderRGB != null ? mBorderRGB.get(position) : DEFAULT_BORDER_RGB;
float alpha = mBorderAlpha != null ? mBorderAlpha.get(position) : DEFAULT_BORDER_ALPHA;
return ReactViewBackgroundDrawable.colorFromAlphaAndRGBComponents(alpha, rgb);
}
public RectF getDirectionAwareBorderInsets() {
final float borderWidth = getBorderWidthOrDefaultTo(0, Spacing.ALL);
final float borderTopWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.TOP);
final float borderBottomWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.BOTTOM);
float borderLeftWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.LEFT);
float borderRightWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.RIGHT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mBorderWidth != null) {
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
float borderStartWidth = mBorderWidth.getRaw(Spacing.START);
float borderEndWidth = mBorderWidth.getRaw(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (YogaConstants.isUndefined(borderStartWidth)) {
borderStartWidth = borderLeftWidth;
}
if (YogaConstants.isUndefined(borderEndWidth)) {
borderEndWidth = borderRightWidth;
}
final float directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth;
final float directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth;
borderLeftWidth = directionAwareBorderLeftWidth;
borderRightWidth = directionAwareBorderRightWidth;
} else {
final float directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth;
final float directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth;
if (!YogaConstants.isUndefined(directionAwareBorderLeftWidth)) {
borderLeftWidth = directionAwareBorderLeftWidth;
}
if (!YogaConstants.isUndefined(directionAwareBorderRightWidth)) {
borderRightWidth = directionAwareBorderRightWidth;
}
}
}
return new RectF(borderLeftWidth, borderTopWidth, borderRightWidth, borderBottomWidth);
}
}
|
package com.facebook.react.views.view;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.annotation.Nullable;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.uimanager.FloatUtil;
import com.facebook.react.uimanager.Spacing;
import com.facebook.yoga.YogaConstants;
import java.util.Arrays;
import java.util.Locale;
/**
* A subclass of {@link Drawable} used for background of {@link ReactViewGroup}. It supports drawing
* background color and borders (including rounded borders) by providing a react friendly API
* (setter for each of those properties).
*
* <p>The implementation tries to allocate as few objects as possible depending on which properties
* are set. E.g. for views with rounded background/borders we allocate {@code
* mInnerClipPathForBorderRadius} and {@code mInnerClipTempRectForBorderRadius}. In case when view
* have a rectangular borders we allocate {@code mBorderWidthResult} and similar. When only
* background color is set we won't allocate any extra/unnecessary objects.
*/
public class ReactViewBackgroundDrawable extends Drawable {
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final int DEFAULT_BORDER_RGB = 0x00FFFFFF & DEFAULT_BORDER_COLOR;
private static final int DEFAULT_BORDER_ALPHA = (0xFF000000 & DEFAULT_BORDER_COLOR) >>> 24;
// ~0 == 0xFFFFFFFF, all bits set to 1.
private static final int ALL_BITS_SET = ~0;
// 0 == 0x00000000, all bits set to 0.
private static final int ALL_BITS_UNSET = 0;
private enum BorderStyle {
SOLID,
DASHED,
DOTTED;
public static @Nullable PathEffect getPathEffect(BorderStyle style, float borderWidth) {
switch (style) {
case SOLID:
return null;
case DASHED:
return new DashPathEffect(
new float[] {borderWidth * 3, borderWidth * 3, borderWidth * 3, borderWidth * 3}, 0);
case DOTTED:
return new DashPathEffect(
new float[] {borderWidth, borderWidth, borderWidth, borderWidth}, 0);
default:
return null;
}
}
};
/* Value at Spacing.ALL index used for rounded borders, whole array used by rectangular borders */
private @Nullable Spacing mBorderWidth;
private @Nullable Spacing mBorderRGB;
private @Nullable Spacing mBorderAlpha;
private @Nullable BorderStyle mBorderStyle;
private @Nullable Path mInnerClipPathForBorderRadius;
private @Nullable Path mOuterClipPathForBorderRadius;
private @Nullable Path mPathForBorderRadiusOutline;
private @Nullable Path mPathForBorder;
private Path mPathForSingleBorder = new Path();
private @Nullable Path mCenterDrawPath;
private @Nullable RectF mInnerClipTempRectForBorderRadius;
private @Nullable RectF mOuterClipTempRectForBorderRadius;
private @Nullable RectF mTempRectForBorderRadiusOutline;
private @Nullable RectF mTempRectForCenterDrawPath;
private @Nullable PointF mInnerTopLeftCorner;
private @Nullable PointF mInnerTopRightCorner;
private @Nullable PointF mInnerBottomRightCorner;
private @Nullable PointF mInnerBottomLeftCorner;
private boolean mNeedUpdatePathForBorderRadius = false;
private float mBorderRadius = YogaConstants.UNDEFINED;
/* Used by all types of background and for drawing borders */
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int mColor = Color.TRANSPARENT;
private int mAlpha = 255;
private @Nullable float[] mBorderCornerRadii;
private final Context mContext;
private int mLayoutDirection;
public enum BorderRadiusLocation {
TOP_LEFT,
TOP_RIGHT,
BOTTOM_RIGHT,
BOTTOM_LEFT,
TOP_START,
TOP_END,
BOTTOM_START,
BOTTOM_END
}
public ReactViewBackgroundDrawable(Context context) {
mContext = context;
}
@Override
public void draw(Canvas canvas) {
updatePathEffect();
if (!hasRoundedBorders()) {
drawRectangularBackgroundWithBorders(canvas);
} else {
drawRoundedBackgroundWithBorders(canvas);
}
}
public boolean hasRoundedBorders() {
if (!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) {
return true;
}
if (mBorderCornerRadii != null) {
for (final float borderRadii : mBorderCornerRadii) {
if (!YogaConstants.isUndefined(borderRadii) && borderRadii > 0) {
return true;
}
}
}
return false;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mNeedUpdatePathForBorderRadius = true;
}
@Override
public void setAlpha(int alpha) {
if (alpha != mAlpha) {
mAlpha = alpha;
invalidateSelf();
}
}
@Override
public int getAlpha() {
return mAlpha;
}
@Override
public void setColorFilter(ColorFilter cf) {
// do nothing
}
@Override
public int getOpacity() {
return ColorUtil.getOpacityFromColor(ColorUtil.multiplyColorAlpha(mColor, mAlpha));
}
/* Android's elevation implementation requires this to be implemented to know where to draw the shadow. */
@Override
public void getOutline(Outline outline) {
if ((!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0)
|| mBorderCornerRadii != null) {
updatePath();
outline.setConvexPath(mPathForBorderRadiusOutline);
} else {
outline.setRect(getBounds());
}
}
public void setBorderWidth(int position, float width) {
if (mBorderWidth == null) {
mBorderWidth = new Spacing();
}
if (!FloatUtil.floatsEqual(mBorderWidth.getRaw(position), width)) {
mBorderWidth.set(position, width);
switch (position) {
case Spacing.ALL:
case Spacing.LEFT:
case Spacing.BOTTOM:
case Spacing.RIGHT:
case Spacing.TOP:
case Spacing.START:
case Spacing.END:
mNeedUpdatePathForBorderRadius = true;
}
invalidateSelf();
}
}
public void setBorderColor(int position, float rgb, float alpha) {
this.setBorderRGB(position, rgb);
this.setBorderAlpha(position, alpha);
}
private void setBorderRGB(int position, float rgb) {
// set RGB component
if (mBorderRGB == null) {
mBorderRGB = new Spacing(DEFAULT_BORDER_RGB);
}
if (!FloatUtil.floatsEqual(mBorderRGB.getRaw(position), rgb)) {
mBorderRGB.set(position, rgb);
invalidateSelf();
}
}
private void setBorderAlpha(int position, float alpha) {
// set Alpha component
if (mBorderAlpha == null) {
mBorderAlpha = new Spacing(DEFAULT_BORDER_ALPHA);
}
if (!FloatUtil.floatsEqual(mBorderAlpha.getRaw(position), alpha)) {
mBorderAlpha.set(position, alpha);
invalidateSelf();
}
}
public void setBorderStyle(@Nullable String style) {
BorderStyle borderStyle =
style == null ? null : BorderStyle.valueOf(style.toUpperCase(Locale.US));
if (mBorderStyle != borderStyle) {
mBorderStyle = borderStyle;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public void setRadius(float radius) {
if (!FloatUtil.floatsEqual(mBorderRadius, radius)) {
mBorderRadius = radius;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public void setRadius(float radius, int position) {
if (mBorderCornerRadii == null) {
mBorderCornerRadii = new float[8];
Arrays.fill(mBorderCornerRadii, YogaConstants.UNDEFINED);
}
if (!FloatUtil.floatsEqual(mBorderCornerRadii[position], radius)) {
mBorderCornerRadii[position] = radius;
mNeedUpdatePathForBorderRadius = true;
invalidateSelf();
}
}
public float getFullBorderRadius() {
return YogaConstants.isUndefined(mBorderRadius) ? 0 : mBorderRadius;
}
public float getBorderRadius(final BorderRadiusLocation location) {
return getBorderRadiusOrDefaultTo(YogaConstants.UNDEFINED, location);
}
public float getBorderRadiusOrDefaultTo(
final float defaultValue, final BorderRadiusLocation location) {
if (mBorderCornerRadii == null) {
return defaultValue;
}
final float radius = mBorderCornerRadii[location.ordinal()];
if (YogaConstants.isUndefined(radius)) {
return defaultValue;
}
return radius;
}
public void setColor(int color) {
mColor = color;
invalidateSelf();
}
/** Similar to Drawable.getLayoutDirection, but available in APIs < 23. */
public int getResolvedLayoutDirection() {
return mLayoutDirection;
}
/** Similar to Drawable.setLayoutDirection, but available in APIs < 23. */
public boolean setResolvedLayoutDirection(int layoutDirection) {
if (mLayoutDirection != layoutDirection) {
mLayoutDirection = layoutDirection;
return onResolvedLayoutDirectionChanged(layoutDirection);
}
return false;
}
/** Similar to Drawable.onLayoutDirectionChanged, but available in APIs < 23. */
public boolean onResolvedLayoutDirectionChanged(int layoutDirection) {
return false;
}
@VisibleForTesting
public int getColor() {
return mColor;
}
private void drawRoundedBackgroundWithBorders(Canvas canvas) {
updatePath();
canvas.save();
int useColor = ColorUtil.multiplyColorAlpha(mColor, mAlpha);
if (Color.alpha(useColor) != 0) { // color is not transparent
mPaint.setColor(useColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawPath(mInnerClipPathForBorderRadius, mPaint);
}
final RectF borderWidth = getDirectionAwareBorderInsets();
int colorLeft = getBorderColor(Spacing.LEFT);
int colorTop = getBorderColor(Spacing.TOP);
int colorRight = getBorderColor(Spacing.RIGHT);
int colorBottom = getBorderColor(Spacing.BOTTOM);
if (borderWidth.top > 0
|| borderWidth.bottom > 0
|| borderWidth.left > 0
|| borderWidth.right > 0) {
// If it's a full and even border draw inner rect path with stroke
final float fullBorderWidth = getFullBorderWidth();
int borderColor = getBorderColor(Spacing.ALL);
if (borderWidth.top == fullBorderWidth
&& borderWidth.bottom == fullBorderWidth
&& borderWidth.left == fullBorderWidth
&& borderWidth.right == fullBorderWidth
&& colorLeft == borderColor
&& colorTop == borderColor
&& colorRight == borderColor
&& colorBottom == borderColor) {
if (fullBorderWidth > 0) {
mPaint.setColor(ColorUtil.multiplyColorAlpha(borderColor, mAlpha));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(fullBorderWidth);
canvas.drawPath(mCenterDrawPath, mPaint);
}
}
// In the case of uneven border widths/colors draw quadrilateral in each direction
else {
mPaint.setStyle(Paint.Style.FILL);
// Draw border
canvas.clipPath(mOuterClipPathForBorderRadius, Region.Op.INTERSECT);
canvas.clipPath(mInnerClipPathForBorderRadius, Region.Op.DIFFERENCE);
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
int colorStart = getBorderColor(Spacing.START);
int colorEnd = getBorderColor(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (!isBorderColorDefined(Spacing.START)) {
colorStart = colorLeft;
}
if (!isBorderColorDefined(Spacing.END)) {
colorEnd = colorRight;
}
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
colorLeft = directionAwareColorLeft;
colorRight = directionAwareColorRight;
} else {
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
final boolean isColorStartDefined = isBorderColorDefined(Spacing.START);
final boolean isColorEndDefined = isBorderColorDefined(Spacing.END);
final boolean isDirectionAwareColorLeftDefined =
isRTL ? isColorEndDefined : isColorStartDefined;
final boolean isDirectionAwareColorRightDefined =
isRTL ? isColorStartDefined : isColorEndDefined;
if (isDirectionAwareColorLeftDefined) {
colorLeft = directionAwareColorLeft;
}
if (isDirectionAwareColorRightDefined) {
colorRight = directionAwareColorRight;
}
}
final float left = mOuterClipTempRectForBorderRadius.left;
final float right = mOuterClipTempRectForBorderRadius.right;
final float top = mOuterClipTempRectForBorderRadius.top;
final float bottom = mOuterClipTempRectForBorderRadius.bottom;
if (borderWidth.left > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = mInnerTopLeftCorner.x;
final float y2 = mInnerTopLeftCorner.y;
final float x3 = mInnerBottomLeftCorner.x;
final float y3 = mInnerBottomLeftCorner.y;
final float x4 = left;
final float y4 = bottom;
drawQuadrilateral(canvas, colorLeft, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.top > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = mInnerTopLeftCorner.x;
final float y2 = mInnerTopLeftCorner.y;
final float x3 = mInnerTopRightCorner.x;
final float y3 = mInnerTopRightCorner.y;
final float x4 = right;
final float y4 = top;
drawQuadrilateral(canvas, colorTop, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.right > 0) {
final float x1 = right;
final float y1 = top;
final float x2 = mInnerTopRightCorner.x;
final float y2 = mInnerTopRightCorner.y;
final float x3 = mInnerBottomRightCorner.x;
final float y3 = mInnerBottomRightCorner.y;
final float x4 = right;
final float y4 = bottom;
drawQuadrilateral(canvas, colorRight, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderWidth.bottom > 0) {
final float x1 = left;
final float y1 = bottom;
final float x2 = mInnerBottomLeftCorner.x;
final float y2 = mInnerBottomLeftCorner.y;
final float x3 = mInnerBottomRightCorner.x;
final float y3 = mInnerBottomRightCorner.y;
final float x4 = right;
final float y4 = bottom;
drawQuadrilateral(canvas, colorBottom, x1, y1, x2, y2, x3, y3, x4, y4);
}
}
}
canvas.restore();
}
private void updatePath() {
if (!mNeedUpdatePathForBorderRadius) {
return;
}
mNeedUpdatePathForBorderRadius = false;
if (mInnerClipPathForBorderRadius == null) {
mInnerClipPathForBorderRadius = new Path();
}
if (mOuterClipPathForBorderRadius == null) {
mOuterClipPathForBorderRadius = new Path();
}
if (mPathForBorderRadiusOutline == null) {
mPathForBorderRadiusOutline = new Path();
}
if (mCenterDrawPath == null) {
mCenterDrawPath = new Path();
}
if (mInnerClipTempRectForBorderRadius == null) {
mInnerClipTempRectForBorderRadius = new RectF();
}
if (mOuterClipTempRectForBorderRadius == null) {
mOuterClipTempRectForBorderRadius = new RectF();
}
if (mTempRectForBorderRadiusOutline == null) {
mTempRectForBorderRadiusOutline = new RectF();
}
if (mTempRectForCenterDrawPath == null) {
mTempRectForCenterDrawPath = new RectF();
}
mInnerClipPathForBorderRadius.reset();
mOuterClipPathForBorderRadius.reset();
mPathForBorderRadiusOutline.reset();
mCenterDrawPath.reset();
mInnerClipTempRectForBorderRadius.set(getBounds());
mOuterClipTempRectForBorderRadius.set(getBounds());
mTempRectForBorderRadiusOutline.set(getBounds());
mTempRectForCenterDrawPath.set(getBounds());
final RectF borderWidth = getDirectionAwareBorderInsets();
mInnerClipTempRectForBorderRadius.top += borderWidth.top;
mInnerClipTempRectForBorderRadius.bottom -= borderWidth.bottom;
mInnerClipTempRectForBorderRadius.left += borderWidth.left;
mInnerClipTempRectForBorderRadius.right -= borderWidth.right;
mTempRectForCenterDrawPath.top += borderWidth.top * 0.5f;
mTempRectForCenterDrawPath.bottom -= borderWidth.bottom * 0.5f;
mTempRectForCenterDrawPath.left += borderWidth.left * 0.5f;
mTempRectForCenterDrawPath.right -= borderWidth.right * 0.5f;
final float borderRadius = getFullBorderRadius();
float topLeftRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_LEFT);
float topRightRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_RIGHT);
float bottomLeftRadius =
getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_LEFT);
float bottomRightRadius =
getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_RIGHT);
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
float topStartRadius = getBorderRadius(BorderRadiusLocation.TOP_START);
float topEndRadius = getBorderRadius(BorderRadiusLocation.TOP_END);
float bottomStartRadius = getBorderRadius(BorderRadiusLocation.BOTTOM_START);
float bottomEndRadius = getBorderRadius(BorderRadiusLocation.BOTTOM_END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (YogaConstants.isUndefined(topStartRadius)) {
topStartRadius = topLeftRadius;
}
if (YogaConstants.isUndefined(topEndRadius)) {
topEndRadius = topRightRadius;
}
if (YogaConstants.isUndefined(bottomStartRadius)) {
bottomStartRadius = bottomLeftRadius;
}
if (YogaConstants.isUndefined(bottomEndRadius)) {
bottomEndRadius = bottomRightRadius;
}
final float directionAwareTopLeftRadius = isRTL ? topEndRadius : topStartRadius;
final float directionAwareTopRightRadius = isRTL ? topStartRadius : topEndRadius;
final float directionAwareBottomLeftRadius = isRTL ? bottomEndRadius : bottomStartRadius;
final float directionAwareBottomRightRadius = isRTL ? bottomStartRadius : bottomEndRadius;
topLeftRadius = directionAwareTopLeftRadius;
topRightRadius = directionAwareTopRightRadius;
bottomLeftRadius = directionAwareBottomLeftRadius;
bottomRightRadius = directionAwareBottomRightRadius;
} else {
final float directionAwareTopLeftRadius = isRTL ? topEndRadius : topStartRadius;
final float directionAwareTopRightRadius = isRTL ? topStartRadius : topEndRadius;
final float directionAwareBottomLeftRadius = isRTL ? bottomEndRadius : bottomStartRadius;
final float directionAwareBottomRightRadius = isRTL ? bottomStartRadius : bottomEndRadius;
if (!YogaConstants.isUndefined(directionAwareTopLeftRadius)) {
topLeftRadius = directionAwareTopLeftRadius;
}
if (!YogaConstants.isUndefined(directionAwareTopRightRadius)) {
topRightRadius = directionAwareTopRightRadius;
}
if (!YogaConstants.isUndefined(directionAwareBottomLeftRadius)) {
bottomLeftRadius = directionAwareBottomLeftRadius;
}
if (!YogaConstants.isUndefined(directionAwareBottomRightRadius)) {
bottomRightRadius = directionAwareBottomRightRadius;
}
}
final float innerTopLeftRadiusX = Math.max(topLeftRadius - borderWidth.left, 0);
final float innerTopLeftRadiusY = Math.max(topLeftRadius - borderWidth.top, 0);
final float innerTopRightRadiusX = Math.max(topRightRadius - borderWidth.right, 0);
final float innerTopRightRadiusY = Math.max(topRightRadius - borderWidth.top, 0);
final float innerBottomRightRadiusX = Math.max(bottomRightRadius - borderWidth.right, 0);
final float innerBottomRightRadiusY = Math.max(bottomRightRadius - borderWidth.bottom, 0);
final float innerBottomLeftRadiusX = Math.max(bottomLeftRadius - borderWidth.left, 0);
final float innerBottomLeftRadiusY = Math.max(bottomLeftRadius - borderWidth.bottom, 0);
mInnerClipPathForBorderRadius.addRoundRect(
mInnerClipTempRectForBorderRadius,
new float[] {
innerTopLeftRadiusX,
innerTopLeftRadiusY,
innerTopRightRadiusX,
innerTopRightRadiusY,
innerBottomRightRadiusX,
innerBottomRightRadiusY,
innerBottomLeftRadiusX,
innerBottomLeftRadiusY,
},
Path.Direction.CW);
mOuterClipPathForBorderRadius.addRoundRect(
mOuterClipTempRectForBorderRadius,
new float[] {
topLeftRadius,
topLeftRadius,
topRightRadius,
topRightRadius,
bottomRightRadius,
bottomRightRadius,
bottomLeftRadius,
bottomLeftRadius
},
Path.Direction.CW);
float extraRadiusForOutline = 0;
if (mBorderWidth != null) {
extraRadiusForOutline = mBorderWidth.get(Spacing.ALL) / 2f;
}
mPathForBorderRadiusOutline.addRoundRect(
mTempRectForBorderRadiusOutline,
new float[] {
topLeftRadius + extraRadiusForOutline,
topLeftRadius + extraRadiusForOutline,
topRightRadius + extraRadiusForOutline,
topRightRadius + extraRadiusForOutline,
bottomRightRadius + extraRadiusForOutline,
bottomRightRadius + extraRadiusForOutline,
bottomLeftRadius + extraRadiusForOutline,
bottomLeftRadius + extraRadiusForOutline
},
Path.Direction.CW);
mCenterDrawPath.addRoundRect(
mTempRectForCenterDrawPath,
new float[] {
Math.max(
topLeftRadius - borderWidth.left * 0.5f,
(borderWidth.left > 0.0f) ? (topLeftRadius / borderWidth.left) : 0.0f),
Math.max(
topLeftRadius - borderWidth.top * 0.5f,
(borderWidth.top > 0.0f) ? (topLeftRadius / borderWidth.top) : 0.0f),
Math.max(
topRightRadius - borderWidth.right * 0.5f,
(borderWidth.right > 0.0f) ? (topRightRadius / borderWidth.right) : 0.0f),
Math.max(
topRightRadius - borderWidth.top * 0.5f,
(borderWidth.top > 0.0f) ? (topRightRadius / borderWidth.top) : 0.0f),
Math.max(
bottomRightRadius - borderWidth.right * 0.5f,
(borderWidth.right > 0.0f) ? (bottomRightRadius / borderWidth.right) : 0.0f),
Math.max(
bottomRightRadius - borderWidth.bottom * 0.5f,
(borderWidth.bottom > 0.0f) ? (bottomRightRadius / borderWidth.bottom) : 0.0f),
Math.max(
bottomLeftRadius - borderWidth.left * 0.5f,
(borderWidth.left > 0.0f) ? (bottomLeftRadius / borderWidth.left) : 0.0f),
Math.max(
bottomLeftRadius - borderWidth.bottom * 0.5f,
(borderWidth.bottom > 0.0f) ? (bottomLeftRadius / borderWidth.bottom) : 0.0f)
},
Path.Direction.CW);
if (mInnerTopLeftCorner == null) {
mInnerTopLeftCorner = new PointF();
}
/** Compute mInnerTopLeftCorner */
mInnerTopLeftCorner.x = mInnerClipTempRectForBorderRadius.left;
mInnerTopLeftCorner.y = mInnerClipTempRectForBorderRadius.top;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.top,
mInnerClipTempRectForBorderRadius.left + 2 * innerTopLeftRadiusX,
mInnerClipTempRectForBorderRadius.top + 2 * innerTopLeftRadiusY,
// Line Start
mOuterClipTempRectForBorderRadius.left,
mOuterClipTempRectForBorderRadius.top,
// Line End
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.top,
// Result
mInnerTopLeftCorner);
/** Compute mInnerBottomLeftCorner */
if (mInnerBottomLeftCorner == null) {
mInnerBottomLeftCorner = new PointF();
}
mInnerBottomLeftCorner.x = mInnerClipTempRectForBorderRadius.left;
mInnerBottomLeftCorner.y = mInnerClipTempRectForBorderRadius.bottom;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.bottom - 2 * innerBottomLeftRadiusY,
mInnerClipTempRectForBorderRadius.left + 2 * innerBottomLeftRadiusX,
mInnerClipTempRectForBorderRadius.bottom,
// Line Start
mOuterClipTempRectForBorderRadius.left,
mOuterClipTempRectForBorderRadius.bottom,
// Line End
mInnerClipTempRectForBorderRadius.left,
mInnerClipTempRectForBorderRadius.bottom,
// Result
mInnerBottomLeftCorner);
/** Compute mInnerTopRightCorner */
if (mInnerTopRightCorner == null) {
mInnerTopRightCorner = new PointF();
}
mInnerTopRightCorner.x = mInnerClipTempRectForBorderRadius.right;
mInnerTopRightCorner.y = mInnerClipTempRectForBorderRadius.top;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.right - 2 * innerTopRightRadiusX,
mInnerClipTempRectForBorderRadius.top,
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.top + 2 * innerTopRightRadiusY,
// Line Start
mOuterClipTempRectForBorderRadius.right,
mOuterClipTempRectForBorderRadius.top,
// Line End
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.top,
// Result
mInnerTopRightCorner);
/** Compute mInnerBottomRightCorner */
if (mInnerBottomRightCorner == null) {
mInnerBottomRightCorner = new PointF();
}
mInnerBottomRightCorner.x = mInnerClipTempRectForBorderRadius.right;
mInnerBottomRightCorner.y = mInnerClipTempRectForBorderRadius.bottom;
getEllipseIntersectionWithLine(
// Ellipse Bounds
mInnerClipTempRectForBorderRadius.right - 2 * innerBottomRightRadiusX,
mInnerClipTempRectForBorderRadius.bottom - 2 * innerBottomRightRadiusY,
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.bottom,
// Line Start
mOuterClipTempRectForBorderRadius.right,
mOuterClipTempRectForBorderRadius.bottom,
// Line End
mInnerClipTempRectForBorderRadius.right,
mInnerClipTempRectForBorderRadius.bottom,
// Result
mInnerBottomRightCorner);
}
private static void getEllipseIntersectionWithLine(
double ellipseBoundsLeft,
double ellipseBoundsTop,
double ellipseBoundsRight,
double ellipseBoundsBottom,
double lineStartX,
double lineStartY,
double lineEndX,
double lineEndY,
PointF result) {
final double ellipseCenterX = (ellipseBoundsLeft + ellipseBoundsRight) / 2;
final double ellipseCenterY = (ellipseBoundsTop + ellipseBoundsBottom) / 2;
/**
* Step 1:
*
* <p>Translate the line so that the ellipse is at the origin.
*
* <p>Why? It makes the math easier by changing the ellipse equation from ((x -
* ellipseCenterX)/a)^2 + ((y - ellipseCenterY)/b)^2 = 1 to (x/a)^2 + (y/b)^2 = 1.
*/
lineStartX -= ellipseCenterX;
lineStartY -= ellipseCenterY;
lineEndX -= ellipseCenterX;
lineEndY -= ellipseCenterY;
/**
* Step 2:
*
* <p>Ellipse equation: (x/a)^2 + (y/b)^2 = 1 Line equation: y = mx + c
*/
final double a = Math.abs(ellipseBoundsRight - ellipseBoundsLeft) / 2;
final double b = Math.abs(ellipseBoundsBottom - ellipseBoundsTop) / 2;
final double m = (lineEndY - lineStartY) / (lineEndX - lineStartX);
final double c = lineStartY - m * lineStartX; // Just a point on the line
/**
* Step 3:
*
* <p>Substitute the Line equation into the Ellipse equation. Solve for x. Eventually, you'll
* have to use the quadratic formula.
*
* <p>Quadratic formula: Ax^2 + Bx + C = 0
*/
final double A = (b * b + a * a * m * m);
final double B = 2 * a * a * c * m;
final double C = (a * a * (c * c - b * b));
/**
* Step 4:
*
* <p>Apply Quadratic formula. D = determinant / 2A
*/
final double D = Math.sqrt(-C / A + Math.pow(B / (2 * A), 2));
final double x2 = -B / (2 * A) - D;
final double y2 = m * x2 + c;
/**
* Step 5:
*
* <p>Undo the space transformation in Step 5.
*/
final double x = x2 + ellipseCenterX;
final double y = y2 + ellipseCenterY;
if (!Double.isNaN(x) && !Double.isNaN(y)) {
result.x = (float) x;
result.y = (float) y;
}
}
public float getBorderWidthOrDefaultTo(final float defaultValue, final int spacingType) {
if (mBorderWidth == null) {
return defaultValue;
}
final float width = mBorderWidth.getRaw(spacingType);
if (YogaConstants.isUndefined(width)) {
return defaultValue;
}
return width;
}
/** Set type of border */
private void updatePathEffect() {
// Used for rounded border and rounded background
PathEffect mPathEffectForBorderStyle =
mBorderStyle != null ? BorderStyle.getPathEffect(mBorderStyle, getFullBorderWidth()) : null;
mPaint.setPathEffect(mPathEffectForBorderStyle);
}
private void updatePathEffect(int borderWidth) {
PathEffect pathEffectForBorderStyle = null;
if (mBorderStyle != null) {
pathEffectForBorderStyle = BorderStyle.getPathEffect(mBorderStyle, borderWidth);
}
mPaint.setPathEffect(pathEffectForBorderStyle);
}
/** For rounded borders we use default "borderWidth" property. */
public float getFullBorderWidth() {
return (mBorderWidth != null && !YogaConstants.isUndefined(mBorderWidth.getRaw(Spacing.ALL)))
? mBorderWidth.getRaw(Spacing.ALL)
: 0f;
}
/**
* Quickly determine if all the set border colors are equal. Bitwise AND all the set colors
* together, then OR them all together. If the AND and the OR are the same, then the colors are
* compatible, so return this color.
*
* <p>Used to avoid expensive path creation and expensive calls to canvas.drawPath
*
* @return A compatible border color, or zero if the border colors are not compatible.
*/
private static int fastBorderCompatibleColorOrZero(
int borderLeft,
int borderTop,
int borderRight,
int borderBottom,
int colorLeft,
int colorTop,
int colorRight,
int colorBottom) {
int andSmear =
(borderLeft > 0 ? colorLeft : ALL_BITS_SET)
& (borderTop > 0 ? colorTop : ALL_BITS_SET)
& (borderRight > 0 ? colorRight : ALL_BITS_SET)
& (borderBottom > 0 ? colorBottom : ALL_BITS_SET);
int orSmear =
(borderLeft > 0 ? colorLeft : ALL_BITS_UNSET)
| (borderTop > 0 ? colorTop : ALL_BITS_UNSET)
| (borderRight > 0 ? colorRight : ALL_BITS_UNSET)
| (borderBottom > 0 ? colorBottom : ALL_BITS_UNSET);
return andSmear == orSmear ? andSmear : 0;
}
private void drawRectangularBackgroundWithBorders(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
int useColor = ColorUtil.multiplyColorAlpha(mColor, mAlpha);
if (Color.alpha(useColor) != 0) { // color is not transparent
mPaint.setColor(useColor);
canvas.drawRect(getBounds(), mPaint);
}
final RectF borderWidth = getDirectionAwareBorderInsets();
final int borderLeft = Math.round(borderWidth.left);
final int borderTop = Math.round(borderWidth.top);
final int borderRight = Math.round(borderWidth.right);
final int borderBottom = Math.round(borderWidth.bottom);
// maybe draw borders?
if (borderLeft > 0 || borderRight > 0 || borderTop > 0 || borderBottom > 0) {
Rect bounds = getBounds();
int colorLeft = getBorderColor(Spacing.LEFT);
int colorTop = getBorderColor(Spacing.TOP);
int colorRight = getBorderColor(Spacing.RIGHT);
int colorBottom = getBorderColor(Spacing.BOTTOM);
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
int colorStart = getBorderColor(Spacing.START);
int colorEnd = getBorderColor(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (!isBorderColorDefined(Spacing.START)) {
colorStart = colorLeft;
}
if (!isBorderColorDefined(Spacing.END)) {
colorEnd = colorRight;
}
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
colorLeft = directionAwareColorLeft;
colorRight = directionAwareColorRight;
} else {
final int directionAwareColorLeft = isRTL ? colorEnd : colorStart;
final int directionAwareColorRight = isRTL ? colorStart : colorEnd;
final boolean isColorStartDefined = isBorderColorDefined(Spacing.START);
final boolean isColorEndDefined = isBorderColorDefined(Spacing.END);
final boolean isDirectionAwareColorLeftDefined =
isRTL ? isColorEndDefined : isColorStartDefined;
final boolean isDirectionAwareColorRightDefined =
isRTL ? isColorStartDefined : isColorEndDefined;
if (isDirectionAwareColorLeftDefined) {
colorLeft = directionAwareColorLeft;
}
if (isDirectionAwareColorRightDefined) {
colorRight = directionAwareColorRight;
}
}
int left = bounds.left;
int top = bounds.top;
// Check for fast path to border drawing.
int fastBorderColor =
fastBorderCompatibleColorOrZero(
borderLeft,
borderTop,
borderRight,
borderBottom,
colorLeft,
colorTop,
colorRight,
colorBottom);
if (fastBorderColor != 0) {
if (Color.alpha(fastBorderColor) != 0) {
// Border color is not transparent.
int right = bounds.right;
int bottom = bounds.bottom;
mPaint.setColor(fastBorderColor);
mPaint.setStyle(Paint.Style.STROKE);
if (borderLeft > 0) {
mPathForSingleBorder.reset();
int width = Math.round(borderWidth.left);
updatePathEffect(width);
mPaint.setStrokeWidth(width);
mPathForSingleBorder.moveTo(left, top - borderWidth.top / 2);
mPathForSingleBorder.lineTo(left, bottom + borderWidth.bottom / 2);
canvas.drawPath(mPathForSingleBorder, mPaint);
}
if (borderTop > 0) {
mPathForSingleBorder.reset();
int width = Math.round(borderWidth.top);
updatePathEffect(width);
mPaint.setStrokeWidth(width);
mPathForSingleBorder.moveTo(left, top);
mPathForSingleBorder.lineTo(right, top);
canvas.drawPath(mPathForSingleBorder, mPaint);
}
if (borderRight > 0) {
mPathForSingleBorder.reset();
int width = Math.round(borderWidth.right);
updatePathEffect(width);
mPaint.setStrokeWidth(width);
mPathForSingleBorder.moveTo(right, top - borderWidth.top / 2);
mPathForSingleBorder.lineTo(right, bottom + borderWidth.bottom / 2);
canvas.drawPath(mPathForSingleBorder, mPaint);
}
if (borderBottom > 0) {
mPathForSingleBorder.reset();
int width = Math.round(borderWidth.bottom);
updatePathEffect(width);
mPaint.setStrokeWidth(width);
mPathForSingleBorder.moveTo(left, bottom);
mPathForSingleBorder.lineTo(right, bottom);
canvas.drawPath(mPathForSingleBorder, mPaint);
}
}
} else {
// If the path drawn previously is of the same color,
// there would be a slight white space between borders
// with anti-alias set to true.
// Therefore we need to disable anti-alias, and
// after drawing is done, we will re-enable it.
mPaint.setAntiAlias(false);
int width = bounds.width();
int height = bounds.height();
if (borderLeft > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = left + borderLeft;
final float y2 = top + borderTop;
final float x3 = left + borderLeft;
final float y3 = top + height - borderBottom;
final float x4 = left;
final float y4 = top + height;
drawQuadrilateral(canvas, colorLeft, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderTop > 0) {
final float x1 = left;
final float y1 = top;
final float x2 = left + borderLeft;
final float y2 = top + borderTop;
final float x3 = left + width - borderRight;
final float y3 = top + borderTop;
final float x4 = left + width;
final float y4 = top;
drawQuadrilateral(canvas, colorTop, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderRight > 0) {
final float x1 = left + width;
final float y1 = top;
final float x2 = left + width;
final float y2 = top + height;
final float x3 = left + width - borderRight;
final float y3 = top + height - borderBottom;
final float x4 = left + width - borderRight;
final float y4 = top + borderTop;
drawQuadrilateral(canvas, colorRight, x1, y1, x2, y2, x3, y3, x4, y4);
}
if (borderBottom > 0) {
final float x1 = left;
final float y1 = top + height;
final float x2 = left + width;
final float y2 = top + height;
final float x3 = left + width - borderRight;
final float y3 = top + height - borderBottom;
final float x4 = left + borderLeft;
final float y4 = top + height - borderBottom;
drawQuadrilateral(canvas, colorBottom, x1, y1, x2, y2, x3, y3, x4, y4);
}
// re-enable anti alias
mPaint.setAntiAlias(true);
}
}
}
private void drawQuadrilateral(
Canvas canvas,
int fillColor,
float x1,
float y1,
float x2,
float y2,
float x3,
float y3,
float x4,
float y4) {
if (fillColor == Color.TRANSPARENT) {
return;
}
if (mPathForBorder == null) {
mPathForBorder = new Path();
}
mPaint.setColor(fillColor);
mPathForBorder.reset();
mPathForBorder.moveTo(x1, y1);
mPathForBorder.lineTo(x2, y2);
mPathForBorder.lineTo(x3, y3);
mPathForBorder.lineTo(x4, y4);
mPathForBorder.lineTo(x1, y1);
canvas.drawPath(mPathForBorder, mPaint);
}
private int getBorderWidth(int position) {
if (mBorderWidth == null) {
return 0;
}
final float width = mBorderWidth.get(position);
return YogaConstants.isUndefined(width) ? -1 : Math.round(width);
}
private static int colorFromAlphaAndRGBComponents(float alpha, float rgb) {
int rgbComponent = 0x00FFFFFF & (int) rgb;
int alphaComponent = 0xFF000000 & ((int) alpha) << 24;
return rgbComponent | alphaComponent;
}
private boolean isBorderColorDefined(int position) {
final float rgb = mBorderRGB != null ? mBorderRGB.get(position) : YogaConstants.UNDEFINED;
final float alpha = mBorderAlpha != null ? mBorderAlpha.get(position) : YogaConstants.UNDEFINED;
return !YogaConstants.isUndefined(rgb) && !YogaConstants.isUndefined(alpha);
}
private int getBorderColor(int position) {
float rgb = mBorderRGB != null ? mBorderRGB.get(position) : DEFAULT_BORDER_RGB;
float alpha = mBorderAlpha != null ? mBorderAlpha.get(position) : DEFAULT_BORDER_ALPHA;
return ReactViewBackgroundDrawable.colorFromAlphaAndRGBComponents(alpha, rgb);
}
@TargetApi(LOLLIPOP)
public RectF getDirectionAwareBorderInsets() {
final float borderWidth = getBorderWidthOrDefaultTo(0, Spacing.ALL);
final float borderTopWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.TOP);
final float borderBottomWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.BOTTOM);
float borderLeftWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.LEFT);
float borderRightWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.RIGHT);
if (mBorderWidth != null) {
final boolean isRTL = getResolvedLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
float borderStartWidth = mBorderWidth.getRaw(Spacing.START);
float borderEndWidth = mBorderWidth.getRaw(Spacing.END);
if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)) {
if (YogaConstants.isUndefined(borderStartWidth)) {
borderStartWidth = borderLeftWidth;
}
if (YogaConstants.isUndefined(borderEndWidth)) {
borderEndWidth = borderRightWidth;
}
final float directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth;
final float directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth;
borderLeftWidth = directionAwareBorderLeftWidth;
borderRightWidth = directionAwareBorderRightWidth;
} else {
final float directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth;
final float directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth;
if (!YogaConstants.isUndefined(directionAwareBorderLeftWidth)) {
borderLeftWidth = directionAwareBorderLeftWidth;
}
if (!YogaConstants.isUndefined(directionAwareBorderRightWidth)) {
borderRightWidth = directionAwareBorderRightWidth;
}
}
}
return new RectF(borderLeftWidth, borderTopWidth, borderRightWidth, borderBottomWidth);
}
}
|
package org.encog.neural.networks;
import junit.framework.Assert;
import org.encog.mathutil.randomize.ConsistentRandomizer;
import org.encog.mathutil.randomize.NguyenWidrowRandomizer;
import org.encog.mathutil.randomize.RangeRandomizer;
import org.encog.neural.activation.ActivationSigmoid;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.training.Train;
public class NetworkUtil {
public static BasicNetwork createXORNetworkUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
//network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new ConsistentRandomizer(-1,1)).randomize(network);
return network;
}
public static BasicNetwork createXORNetworkRangeRandomizedUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new RangeRandomizer(-1,1)).randomize( network);
return network;
}
public static BasicNetwork createXORNetworknNguyenWidrowUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new NguyenWidrowRandomizer(-1,1)).randomize( network );
return network;
}
public static void testTraining(Train train, double requiredImprove)
{
train.iteration();
double error1 = train.getError();
for(int i=0;i<10;i++)
train.iteration();
double error2 = train.getError();
double improve = (error1-error2)/error1;
Assert.assertTrue("Improve rate too low for " + train.getClass().getSimpleName() +
",Improve="+improve+",Needed="+requiredImprove, improve>=requiredImprove);
}
}
|
package org.encog.neural.networks;
import junit.framework.Assert;
import org.encog.math.randomize.BasicRandomizer;
import org.encog.math.randomize.ConsistentRandomizer;
import org.encog.math.randomize.NguyenWidrowRandomizer;
import org.encog.math.randomize.RangeRandomizer;
import org.encog.neural.activation.ActivationSigmoid;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.training.Train;
public class NetworkUtil {
public static BasicNetwork createXORNetworkUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new ConsistentRandomizer(-1,1)).randomize(network);
return network;
}
public static BasicNetwork createXORNetworkRangeRandomizedUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new RangeRandomizer(-1,1)).randomize( network);
return network;
}
public static BasicNetwork createXORNetworknNguyenWidrowUntrained()
{
// random matrix data. However, it provides a constant starting point
// for the unit tests.
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
(new NguyenWidrowRandomizer(-1,1)).randomize( network );
return network;
}
public static void testTraining(Train train, double requiredImprove)
{
train.iteration();
double error1 = train.getError();
for(int i=0;i<10;i++)
train.iteration();
double error2 = train.getError();
double improve = (error1-error2)/error1;
Assert.assertTrue("Improve rate too low for " + train.getClass().getSimpleName() +
",Improve="+improve+",Needed="+requiredImprove, improve>=requiredImprove);
}
}
|
package org.pentaho.di.core.row;
import java.math.BigDecimal;
import java.util.Date;
import junit.framework.TestCase;
/**
* Test functionality in ValueMeta
*
* @author sboden
*/
public class ValueMetaTest extends TestCase
{
/**
* Compare to byte arrays for equality.
*
* @param b1 1st byte array
* @param b2 2nd byte array
*
* @return true if equal
*/
private boolean byteCompare(byte[] b1, byte[] b2)
{
if ( b1.length != b2.length )
return false;
int idx = 0;
while ( idx < b1.length )
{
if ( b1[idx] != b2[idx] )
return false;
idx++;
}
return true;
}
public void testCvtStringToBinaryString() throws Exception
{
ValueMeta val1 = new ValueMeta("STR1", ValueMetaInterface.TYPE_STRING);
val1.setLength(6);
val1.setStringEncoding("UTF8");
// No truncating or padding!!!
byte b1[] = val1.getBinary("PDI123");
assertTrue(byteCompare(b1, new byte[] { 'P', 'D', 'I', '1', '2', '3' }));
byte b2[] = val1.getBinary("PDI");
assertTrue(byteCompare(b2, new byte[] { 'P', 'D', 'I' }));
byte b3[] = val1.getBinary("PDI123456");
assertTrue(byteCompare(b3, new byte[] { 'P', 'D', 'I', '1', '2', '3', '4', '5', '6' }));
ValueMeta val2 = new ValueMeta("STR2", ValueMetaInterface.TYPE_STRING);
val2.setLength(1);
byte b4[] = val2.getBinary("PDI123");
assertTrue(byteCompare(b4, new byte[] { 'P', 'D', 'I', '1', '2', '3' }));
byte b5[] = val2.getBinary("PDI");
assertTrue(byteCompare(b5, new byte[] { 'P', 'D', 'I' }));
byte b6[] = val2.getBinary("PDI123456");
assertTrue(byteCompare(b6, new byte[] { 'P', 'D', 'I', '1', '2', '3', '4', '5', '6' }));
}
public void testCvtStringBinaryString() throws Exception
{
ValueMeta val1 = new ValueMeta("STR1", ValueMetaInterface.TYPE_STRING);
val1.setLength(6);
val1.setStringEncoding("UTF8");
ValueMeta val2 = new ValueMeta("BINSTR1", ValueMetaInterface.TYPE_STRING, ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
val2.setStorageMetadata(val1);
val2.setLength(6);
val2.setStringEncoding("UTF8");
String str1 = val2.getString(val1.getBinary("PDI123"));
assertTrue("PDI123".equals(str1));
String str2 = val2.getString(val1.getBinary("PDI"));
assertTrue("PDI".equals(str2));
String str3 = val2.getString(val1.getBinary("PDI123456"));
assertTrue("PDI123456".equals(str3));
}
public void testIntegerToStringToInteger() throws Exception
{
ValueMetaInterface intValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_INTEGER);
intValueMeta.setConversionMask(null);
intValueMeta.setLength(7);
Long originalValue = new Long(123L);
String string = intValueMeta.getString(originalValue);
assertEquals(" 0000123", string);
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
strValueMeta.setConversionMetadata(intValueMeta);
Long x = (Long) strValueMeta.convertDataUsingConversionMetaData(string);
assertEquals(originalValue, x);
}
public void testNumberToStringToNumber() throws Exception
{
ValueMetaInterface numValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_NUMBER);
numValueMeta.setConversionMask(null);
numValueMeta.setLength(7,3);
numValueMeta.setDecimalSymbol(",");
numValueMeta.setGroupingSymbol(".");
Double originalValue = new Double(123.456);
String string = numValueMeta.getString(originalValue);
assertEquals(" 0123,456", string);
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
strValueMeta.setConversionMetadata(numValueMeta);
Double x = (Double) strValueMeta.convertDataUsingConversionMetaData(string);
assertEquals(originalValue, x);
}
public void testBigNumberToStringToBigNumber() throws Exception
{
ValueMetaInterface numValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_BIGNUMBER);
numValueMeta.setLength(42,9);
numValueMeta.setDecimalSymbol(",");
numValueMeta.setGroupingSymbol(".");
BigDecimal originalValue = new BigDecimal("34039423484343123.443489056");
String string = numValueMeta.getString(originalValue);
assertEquals("34039423484343123.443489056", string);
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
strValueMeta.setConversionMetadata(numValueMeta);
BigDecimal x = (BigDecimal) strValueMeta.convertDataUsingConversionMetaData(string);
assertEquals(originalValue, x);
}
public void testDateToStringToDate() throws Exception
{
ValueMetaInterface datValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_DATE);
datValueMeta.setConversionMask("yyyy - MM - dd HH:mm:ss'('SSS')'");
Date originalValue = new Date(7258114799999L);
String string = datValueMeta.getString(originalValue);
assertEquals("2199 - 12 - 31 23:59:59(999)", string);
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
strValueMeta.setConversionMetadata(datValueMeta);
Date x = (Date) strValueMeta.convertDataUsingConversionMetaData(string);
assertEquals(originalValue, x);
}
public void testConvertDataDate() throws Exception
{
ValueMetaInterface source = new ValueMeta("src", ValueMetaInterface.TYPE_STRING);
source.setConversionMask("SSS.ss:mm:HH dd/MM/yyyy");
ValueMetaInterface target = new ValueMeta("tgt", ValueMetaInterface.TYPE_DATE);
Date date = (Date) target.convertData(source, "999.59:59:23 31/12/2007");
assertEquals(new Date(1199141999999L), date);
target.setConversionMask("yy/MM/dd HH:mm");
String string = (String) source.convertData(target, date);
assertEquals("07/12/31 23:59", string);
}
public void testConvertDataInteger() throws Exception
{
ValueMetaInterface source = new ValueMeta("src", ValueMetaInterface.TYPE_STRING);
source.setConversionMask("
source.setLength(12,3);
source.setDecimalSymbol(",");
source.setGroupingSymbol(".");
ValueMetaInterface target = new ValueMeta("tgt", ValueMetaInterface.TYPE_INTEGER);
Long d = (Long) target.convertData(source, " 2.837");
assertEquals(2837L, d.longValue());
target.setConversionMask("
target.setLength(12,4);
target.setDecimalSymbol(".");
target.setGroupingSymbol("'");
String string = (String) source.convertData(target, d);
assertEquals("2'837.00", string);
}
public void testConvertDataNumber() throws Exception
{
ValueMetaInterface source = new ValueMeta("src", ValueMetaInterface.TYPE_STRING);
source.setConversionMask("
source.setLength(3,0);
source.setDecimalSymbol(",");
source.setGroupingSymbol(".");
ValueMetaInterface target = new ValueMeta("tgt", ValueMetaInterface.TYPE_NUMBER);
Double d = (Double) target.convertData(source, "123.456.789,012");
assertEquals(123456789.012, d);
target.setConversionMask("
target.setLength(12,4);
target.setDecimalSymbol(".");
target.setGroupingSymbol("'");
String string = (String) source.convertData(target, d);
assertEquals("123'456'789.01", string);
}
/**
* Lazy conversion is used to read data from disk in a binary format.
* The data itself is not converted from the byte[] to Integer, rather left untouched until it's needed.
*
* However at that time we do need it we should get the correct value back.
* @throws Exception
*/
public void testLazyConversionInteger() throws Exception
{
byte[] data = ("1234").getBytes();
ValueMetaInterface intValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_INTEGER);
intValueMeta.setConversionMask(null);
intValueMeta.setLength(7);
intValueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
intValueMeta.setStorageMetadata(strValueMeta);
Long integerValue = intValueMeta.getInteger(data);
assertEquals(new Long(1234L), integerValue);
Double numberValue = intValueMeta.getNumber(data);
assertEquals(new Double(1234), numberValue);
BigDecimal bigNumberValue = intValueMeta.getBigNumber(data);
assertEquals(new BigDecimal(1234), bigNumberValue);
Date dateValue = intValueMeta.getDate(data);
assertEquals(new Date(1234L), dateValue);
String string = intValueMeta.getString(data);
assertEquals(" 0001234", string);
}
/**
* Lazy conversion is used to read data from disk in a binary format.
* The data itself is not converted from the byte[] to Integer, rather left untouched until it's needed.
*
* However at that time we do need it we should get the correct value back.
* @throws Exception
*/
public void testLazyConversionNumber() throws Exception
{
byte[] data = ("1,234.56").getBytes();
ValueMetaInterface numValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_NUMBER);
numValueMeta.setConversionMask(null);
// The representation formatting options.
numValueMeta.setLength(12,4);
numValueMeta.setDecimalSymbol(",");
numValueMeta.setGroupingSymbol(".");
numValueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// let's explain to the parser how the input data looks like. (the storage metadata)
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
strValueMeta.setConversionMask("#,##0.00");
strValueMeta.setDecimalSymbol(".");
strValueMeta.setGroupingSymbol(",");
numValueMeta.setStorageMetadata(strValueMeta);
Long integerValue = numValueMeta.getInteger(data);
assertEquals(new Long(1235L), integerValue);
Double numberValue = numValueMeta.getNumber(data);
assertEquals(new Double(1234.56), numberValue);
BigDecimal bigNumberValue = numValueMeta.getBigNumber(data);
assertEquals(new BigDecimal(1234.56), bigNumberValue);
Date dateValue = numValueMeta.getDate(data);
assertEquals(new Date(1234L), dateValue);
String string = numValueMeta.getString(data);
assertEquals(" 00001234,5600", string);
// Get the binary data back : has to return exactly the same as we asked ONLY if the formatting options are the same
// In this unit test they are not!
byte[] binaryValue = numValueMeta.getBinaryString(data);
assertTrue(byteCompare((" 00001234,5600").getBytes(), binaryValue));
}
/**
* Lazy conversion is used to read data from disk in a binary format.
* The data itself is not converted from the byte[] to Integer, rather left untouched until it's needed.
*
* However at that time we do need it we should get the correct value back.
* @throws Exception
*/
public void testLazyConversionBigNumber() throws Exception
{
String originalValue = "34983433433212304121900934.5634314343";
byte[] data = originalValue.getBytes();
ValueMetaInterface numValueMeta = new ValueMeta("i", ValueMetaInterface.TYPE_BIGNUMBER);
// The representation formatting options.
numValueMeta.setLength(36,10);
numValueMeta.setDecimalSymbol(",");
numValueMeta.setGroupingSymbol(".");
numValueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// let's explain to the parser how the input data looks like. (the storage metadata)
ValueMetaInterface strValueMeta = new ValueMeta("str", ValueMetaInterface.TYPE_STRING);
numValueMeta.setStorageMetadata(strValueMeta);
// NOTE This is obviously a number that is too large to fit into an Integer or a Number, but this is what we expect to come back.
// Later it might be better to throw exceptions for big-number to integer conversion.
// At the time of writing this unit test is not the case.
// -- Matt
Long integerValue = numValueMeta.getInteger(data);
assertEquals(new Long(-5045838617297571962L), integerValue);
Double numberValue = numValueMeta.getNumber(data);
assertEquals(new Double("3.4983433433212304E25"), numberValue);
BigDecimal bigNumberValue = numValueMeta.getBigNumber(data);
assertEquals(new BigDecimal(originalValue), bigNumberValue);
Date dateValue = numValueMeta.getDate(data);
assertEquals(new Date(-5045838617297571962L), dateValue);
String string = numValueMeta.getString(data);
assertEquals(originalValue, string);
}
public void testCompareIntegersNormalStorageData() throws Exception
{
Long integer1 = new Long(1234L);
Long integer2 = new Long(1235L);
Long integer3 = new Long(1233L);
Long integer4 = new Long(1234L);
Long integer5 = null;
Long integer6 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_INTEGER);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_INTEGER);
assertTrue( one.compare(integer1, integer2) < 0 );
assertTrue( one.compare(integer1, integer3) > 0 );
assertTrue( one.compare(integer1, integer4) == 0 );
assertTrue( one.compare(integer1, integer5) != 0 );
assertTrue( one.compare(integer5, integer6) == 0 );
assertTrue( one.compare(integer1, two, integer2) < 0 );
assertTrue( one.compare(integer1, two, integer3) > 0 );
assertTrue( one.compare(integer1, two, integer4) == 0 );
assertTrue( one.compare(integer1, two, integer5) != 0 );
assertTrue( one.compare(integer5, two, integer6) == 0 );
}
public void testCompareNumbersNormalStorageData() throws Exception
{
Double number1 = new Double(1234.56);
Double number2 = new Double(1235.56);
Double number3 = new Double(1233.56);
Double number4 = new Double(1234.56);
Double number5 = null;
Double number6 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_NUMBER);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_NUMBER);
assertTrue( one.compare(number1, number2) < 0 );
assertTrue( one.compare(number1, number3) > 0 );
assertTrue( one.compare(number1, number4) == 0 );
assertTrue( one.compare(number1, number5) != 0 );
assertTrue( one.compare(number5, number6) == 0 );
assertTrue( one.compare(number1, two, number2) < 0 );
assertTrue( one.compare(number1, two, number3) > 0 );
assertTrue( one.compare(number1, two, number4) == 0 );
assertTrue( one.compare(number1, two, number5) != 0 );
assertTrue( one.compare(number5, two, number6) == 0 );
}
public void testCompareBigNumberNormalStorageData() throws Exception
{
BigDecimal number1 = new BigDecimal("987908798769876.23943409");
BigDecimal number2 = new BigDecimal("999908798769876.23943409");
BigDecimal number3 = new BigDecimal("955908798769876.23943409");
BigDecimal number4 = new BigDecimal("987908798769876.23943409");
BigDecimal number5 = null;
BigDecimal number6 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_BIGNUMBER);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_BIGNUMBER);
assertTrue( one.compare(number1, number2) < 0 );
assertTrue( one.compare(number1, number3) > 0 );
assertTrue( one.compare(number1, number4) == 0 );
assertTrue( one.compare(number1, number5) != 0 );
assertTrue( one.compare(number5, number6) == 0 );
assertTrue( one.compare(number1, two, number2) < 0 );
assertTrue( one.compare(number1, two, number3) > 0 );
assertTrue( one.compare(number1, two, number4) == 0 );
assertTrue( one.compare(number1, two, number5) != 0 );
assertTrue( one.compare(number5, two, number6) == 0 );
}
public void testCompareDatesNormalStorageData() throws Exception
{
Date date1 = new Date();
Date date2 = new Date(date1.getTime()+3600);
Date date3 = new Date(date1.getTime()-3600);
Date date4 = new Date(date1.getTime());
Date date5 = null;
Date date6 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_DATE);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_DATE);
assertTrue( one.compare(date1, date2) < 0 );
assertTrue( one.compare(date1, date3) > 0 );
assertTrue( one.compare(date1, date4) == 0 );
assertTrue( one.compare(date1, date5) != 0 );
assertTrue( one.compare(date5, date6) == 0 );
assertTrue( one.compare(date1, two, date2) < 0 );
assertTrue( one.compare(date1, two, date3) > 0 );
assertTrue( one.compare(date1, two, date4) == 0 );
assertTrue( one.compare(date1, two, date5) != 0 );
assertTrue( one.compare(date5, two, date6) == 0 );
}
public void testCompareBooleanNormalStorageData() throws Exception
{
Boolean boolean1 = new Boolean(false);
Boolean boolean2 = new Boolean(true);
Boolean boolean3 = new Boolean(false);
Boolean boolean4 = null;
Boolean boolean5 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_BOOLEAN);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_BOOLEAN);
assertTrue( one.compare(boolean1, boolean2) < 0 );
assertTrue( one.compare(boolean1, boolean3) == 0 );
assertTrue( one.compare(boolean1, boolean4) != 0 );
assertTrue( one.compare(boolean4, boolean5) == 0 );
assertTrue( one.compare(boolean1, two, boolean2) < 0 );
assertTrue( one.compare(boolean1, two, boolean3) == 0 );
assertTrue( one.compare(boolean1, two, boolean4) != 0 );
assertTrue( one.compare(boolean4, two, boolean5) == 0 );
}
public void testCompareStringsNormalStorageData() throws Exception
{
String string1 = "bbbbb";
String string2 = "ccccc";
String string3 = "aaaaa";
String string4 = "bbbbb";
String string5 = null;
String string6 = null;
ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_STRING);
ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_STRING);
assertTrue( one.compare(string1, string2) < 0 );
assertTrue( one.compare(string1, string3) > 0 );
assertTrue( one.compare(string1, string4) == 0 );
assertTrue( one.compare(string1, string5) != 0 );
assertTrue( one.compare(string5, string6) == 0 );
assertTrue( one.compare(string1, two, string2) < 0 );
assertTrue( one.compare(string1, two, string3) > 0 );
assertTrue( one.compare(string1, two, string4) == 0 );
assertTrue( one.compare(string1, two, string5) != 0 );
assertTrue( one.compare(string5, two, string6) == 0 );
}
}
|
package com.groupon.seleniumgridextras.config;
import com.google.gson.Gson;
import com.groupon.seleniumgridextras.OSChecker;
import com.groupon.seleniumgridextras.SeleniumGridExtras;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class RuntimeConfig {
private static String configFile = "selenium_grid_extras_config.json";
private static Config config = null;
public RuntimeConfig() {
config = new Config();
}
public static String getConfigFile() {
return configFile;
}
public static void setConfigFile(String file) {
configFile = file;
}
public static Config load() {
Config defaultConfig = DefaultConfig.getDefaultConfig();
String configString = readConfigFile(configFile);
if (configString != "") {
config = new Gson().fromJson(configString, Config.class);
} else {
// first time runner
Config config = new Config(false);
config = FirstTimeRunConfig.customiseConfig(config);
config.writeToDisk(configFile);
}
defaultConfig.mergeConfig(config);
return config;
}
public static Config loadDefaults() {
DefaultConfig.getDefaultConfig().writeToDisk(configFile);
return load();
}
public static String getSeleniumGridExtrasJarFile() {
return SeleniumGridExtras.class.getProtectionDomain().getCodeSource().getLocation().getPath();
}
public static String getCurrentHostIP() {
try {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostAddress();
} catch (UnknownHostException error) {
System.out.println(error);
return "";
}
}
public static String getSeleniungGridExtrasHomePath() {
String path = getSeleniumGridExtrasJarFile();
path = path.replaceAll("[\\w-\\d\\.]*\\.jar", "");
if (OSChecker.isWindows()) {
path = OSChecker.toWindowsPath(path);
}
return path;
}
private static String readConfigFile(String filePath) {
String returnString = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = reader.readLine()) != null) {
returnString = returnString + line;
}
} catch (FileNotFoundException error) {
System.out.println("File " + filePath + " does not exist, going to use default configs");
} catch (IOException error) {
System.out.println("Error reading" + filePath + ". Going with default configs");
}
return returnString;
}
public static Config getConfig() {
return config;
}
}
|
package org.springframework.jdbc;
import java.sql.Connection;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
/**
* @task enter type comments
*
* @author <a href="mailto:tcook@interprisesoftware.com">Trevor D. Cook</a>
* @version $Id: JdbcTestCase.java,v 1.2 2003-11-03 15:14:02 johnsonr Exp $
*/
public abstract class JdbcTestCase extends TestCase {
protected MockControl ctrlDataSource;
protected DataSource mockDataSource;
protected MockControl ctrlConnection;
protected Connection mockConnection;
/**
* Set to true if the user wants verification, indicated
* by a call to replay(). We need to make this optional,
* otherwise we setUp() will always result in verification failures
*/
private boolean shouldVerify;
public JdbcTestCase() {
super();
}
/**
* @param name
*/
public JdbcTestCase(String name) {
super(name);
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
this.shouldVerify = false;
super.setUp();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
}
/**
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
// We shouldn't verify unless the user called replay()
if (this.shouldVerify) {
ctrlDataSource.verify();
ctrlConnection.verify();
}
}
protected void replay() {
this.shouldVerify = true;
ctrlDataSource.replay();
ctrlConnection.replay();
}
}
|
package com.gmail.jameshealey1994.simpletowns.commands.command;
import com.gmail.jameshealey1994.simpletowns.SimpleTowns;
import com.gmail.jameshealey1994.simpletowns.events.TownDeleteEvent;
import com.gmail.jameshealey1994.simpletowns.localisation.Localisation;
import com.gmail.jameshealey1994.simpletowns.localisation.LocalisationEntry;
import com.gmail.jameshealey1994.simpletowns.object.Town;
import com.gmail.jameshealey1994.simpletowns.permissions.STPermission;
import com.gmail.jameshealey1994.simpletowns.utils.Logger;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Class representing a delete command.
*
* /... delete <townname> Deletes town named <townname>
*
* @author JamesHealey94 <jameshealey1994.gmail.com>
*/
public class DeleteCommand extends STCommand {
public DeleteCommand() {
this.aliases.add("delete");
this.aliases.add("deletetown");
this.permissions.add(STPermission.DELETE.getPermission());
}
@Override
public boolean execute(SimpleTowns plugin, CommandSender sender, String commandLabel, String[] args) {
final Localisation localisation = plugin.getLocalisation();
if (args.length == 0) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_SPECIFY_TOWN_NAME));
return false;
}
// Check town exists
final String attemptedTownName = args[0];
final Town town = plugin.getTown(attemptedTownName);
if (town == null) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_TOWN_NOT_FOUND, attemptedTownName));
return true;
}
// Check player is town leader or admin
if (sender instanceof Player && !town.getLeaders().contains(sender.getName()) && !sender.hasPermission(STPermission.ADMIN.getPermission())) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_NOT_LEADER, attemptedTownName));
return true;
}
// Delete town locally
plugin.getTowns().remove(town.getName().toLowerCase());
// Delete town from config
final String path = "Towns.";
plugin.getConfig().set(path + town.getName(), null);
// Log to file
new Logger(plugin).log(localisation.get(LocalisationEntry.LOG_TOWN_DELETED, town.getName(), sender.getName()));
// Save config
plugin.saveConfig();
//Create and call TownDeleteEvent
final TownDeleteEvent event = new TownDeleteEvent(town.getName());
plugin.getServer().getPluginManager().callEvent(event);
// Send confimation message to sender
sender.sendMessage(localisation.get(LocalisationEntry.MSG_TOWN_DELETED, town.getName()));
// Broadcast to server
plugin.getServer().broadcastMessage(localisation.get(LocalisationEntry.MSG_TOWN_DELETED_BROADCAST, town.getName()));
return true;
}
@Override
public String getDescription(Localisation localisation) {
return localisation.get(LocalisationEntry.DESCRIPTION_DELETE);
}
}
|
package ualberta.g12.adventurecreator;
import java.util.LinkedList;
import java.util.List;
public class Story extends SModel{
private static final int NEW_STORY_ID = -1;
private String storyTitle;
private String author;
private int id = 1; // TODO: should be unique
private List<Fragment> fragments; // first index in pages is always the
// start page
public Story() {
// No hardcoded strings
// TODO: Move these to res/values/strings.xml
/*
* TODO: Possibly move to a View
* I feel like these should be in the view for creating a new story as
* the default text/hint. It doesn't really make sense for the Model to
* have this
*/
this("Add a title.", "Your pen name here");
}
public Story(String title, String author) {
setStoryTitle(title);
setAuthor(author);
this.fragments = new LinkedList<Fragment>();
}
public String getStoryTitle() {
return storyTitle;
}
public void setStoryTitle(String storyTitle) {
this.storyTitle = storyTitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public List<Fragment> getFragments() {
return fragments;
}
public void addFragment(Fragment newFragment) {
this.fragments.add(newFragment);
}
public boolean removeFragment(Fragment oldFragment) {
return this.fragments.remove(oldFragment);
}
public void setFragments(List<Fragment> f){
this.fragments = f;
}
public void addLinkToNewPage() {
}
public void addLinkToPageInStory(Fragment currentPage, String choiceText, Fragment linkedToPage) {
}
// For merging stories (should happen when a choice is set to a page in
// another story)
public void afterPageLinkedToAnotherStory(Story newStory, Fragment pageLinkedTo,
Choice choiceToSet) {
// adds all pages of newStory to the current story
for (int i = 0; i < newStory.getFragments().size(); i++) {
this.fragments.add(newStory.getFragments().get(i));
}
choiceToSet.setLinkedToPage(pageLinkedTo);
}
// finds isolated pages and sets their isLinkedTo flag to false
// should be run before each time a list of pages in the story is displayed
// or only before the pages are displayed and change flag is true.
// would need to create a change flag
public void findAndMarkIsolatedPages() {
LinkedList<Fragment> copyOfPages = new LinkedList<Fragment>();
// copies pages list
for (int i = 0; i < this.fragments.size(); i++) {
copyOfPages.add(fragments.get(i));
}
// removes all pages from copyOfPages that are referenced
for (int i = 0; i < this.fragments.size(); i++) {
for (int j = 0; j < fragments.get(i).getChoices().size(); j++) {
Fragment tempPage = fragments.get(i).getChoices().get(j).getLinkedToPage();
copyOfPages.remove(tempPage);
}
}
// only unreferenced pages remain
for (int i = 0; i < copyOfPages.size(); i++) {
copyOfPages.get(i).setLinkedTo(false);
}
}
/**
* will get id of the story (should be unique)
* @return
*/
public int getId(){
return this.id;
}
/**
* will set id of the story (should be unique)
* @param newId
*/
public void setId(int newId){
this.id = newId;
}
}
|
package waffle.windows.auth.impl;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Netapi32Util;
import com.sun.jna.platform.win32.Netapi32Util.DomainTrust;
import com.sun.jna.platform.win32.Secur32;
import com.sun.jna.platform.win32.Sspi;
import com.sun.jna.platform.win32.Sspi.CtxtHandle;
import com.sun.jna.platform.win32.Sspi.SecBufferDesc;
import com.sun.jna.platform.win32.Win32Exception;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
import com.sun.jna.ptr.IntByReference;
import waffle.windows.auth.IWindowsAccount;
import waffle.windows.auth.IWindowsAuthProvider;
import waffle.windows.auth.IWindowsComputer;
import waffle.windows.auth.IWindowsCredentialsHandle;
import waffle.windows.auth.IWindowsDomain;
import waffle.windows.auth.IWindowsIdentity;
import waffle.windows.auth.IWindowsSecurityContext;
/**
* Windows Auth Provider.
*
* @author dblock[at]dblock[dot]org
*/
public class WindowsAuthProviderImpl implements IWindowsAuthProvider {
/**
* The Class ContinueContext.
*/
private static class ContinueContext {
/** The continue handle. */
CtxtHandle continueHandle;
/** The server credential. */
IWindowsCredentialsHandle serverCredential;
/**
* Instantiates a new continue context.
*
* @param handle
* the handle
* @param windowsCredential
* the windows credential
*/
public ContinueContext(final CtxtHandle handle, final IWindowsCredentialsHandle windowsCredential) {
this.continueHandle = handle;
this.serverCredential = windowsCredential;
}
}
/** The continue contexts. */
private final Cache<String, ContinueContext> continueContexts;
/**
* Instantiates a new windows auth provider impl.
*/
public WindowsAuthProviderImpl() {
this(30);
}
/**
* A Windows authentication provider.
*
* @param continueContextsTimeout
* Timeout for security contexts in seconds.
*/
public WindowsAuthProviderImpl(final int continueContextsTimeout) {
this.continueContexts = CacheBuilder.newBuilder().expireAfterWrite(continueContextsTimeout, TimeUnit.SECONDS)
.build();
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#acceptSecurityToken(java.lang.String, byte[], java.lang.String)
*/
@Override
public IWindowsSecurityContext acceptSecurityToken(final String connectionId, final byte[] token,
final String securityPackage) {
if (token == null || token.length == 0) {
this.resetSecurityToken(connectionId);
throw new Win32Exception(WinError.SEC_E_INVALID_TOKEN);
}
CtxtHandle continueHandle = null;
IWindowsCredentialsHandle serverCredential;
ContinueContext continueContext = this.continueContexts.asMap().get(connectionId);
if (continueContext != null) {
continueHandle = continueContext.continueHandle;
serverCredential = continueContext.serverCredential;
} else {
serverCredential = new WindowsCredentialsHandleImpl(null, Sspi.SECPKG_CRED_INBOUND, securityPackage);
serverCredential.initialize();
}
WindowsSecurityContextImpl sc;
int rc;
int tokenSize = Sspi.MAX_TOKEN_SIZE;
do {
final SecBufferDesc pbServerToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenSize);
final SecBufferDesc pbClientToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, token);
final IntByReference pfClientContextAttr = new IntByReference();
final CtxtHandle phNewServerContext = new CtxtHandle();
rc = Secur32.INSTANCE.AcceptSecurityContext(serverCredential.getHandle(), continueHandle, pbClientToken,
Sspi.ISC_REQ_CONNECTION, Sspi.SECURITY_NATIVE_DREP, phNewServerContext, pbServerToken,
pfClientContextAttr, null);
sc = new WindowsSecurityContextImpl();
sc.setCredentialsHandle(serverCredential);
sc.setSecurityPackage(securityPackage);
sc.setSecurityContext(phNewServerContext);
switch (rc) {
case WinError.SEC_E_BUFFER_TOO_SMALL:
tokenSize += Sspi.MAX_TOKEN_SIZE;
sc.dispose();
WindowsSecurityContextImpl.dispose(continueHandle);
break;
case WinError.SEC_E_OK:
// the security context received from the client was accepted
this.resetSecurityToken(connectionId);
// if an output token was generated by the function, it must be sent to the client process
if (pbServerToken.pBuffers != null && pbServerToken.cBuffers == 1
&& pbServerToken.pBuffers[0].cbBuffer > 0) {
sc.setToken(pbServerToken.getBytes() == null ? new byte[0] : pbServerToken.getBytes().clone());
}
sc.setContinue(false);
break;
case WinError.SEC_I_CONTINUE_NEEDED:
// the server must send the output token to the client and wait for a returned token
continueContext = new ContinueContext(phNewServerContext, serverCredential);
this.continueContexts.put(connectionId, continueContext);
sc.setToken(pbServerToken.getBytes() == null ? new byte[0] : pbServerToken.getBytes().clone());
sc.setContinue(true);
break;
default:
sc.dispose();
WindowsSecurityContextImpl.dispose(continueHandle);
this.resetSecurityToken(connectionId);
throw new Win32Exception(rc);
}
} while (rc == WinError.SEC_E_BUFFER_TOO_SMALL);
return sc;
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#getCurrentComputer()
*/
@Override
public IWindowsComputer getCurrentComputer() {
try {
return new WindowsComputerImpl(InetAddress.getLocalHost().getHostName());
} catch (final UnknownHostException e) {
throw new RuntimeException(e);
}
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#getDomains()
*/
@Override
public IWindowsDomain[] getDomains() {
final List<IWindowsDomain> domains = new ArrayList<>();
final DomainTrust[] trusts = Netapi32Util.getDomainTrusts();
for (final DomainTrust trust : trusts) {
domains.add(new WindowsDomainImpl(trust));
}
return domains.toArray(new IWindowsDomain[0]);
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#logonDomainUser(java.lang.String, java.lang.String,
* java.lang.String)
*/
@Override
public IWindowsIdentity logonDomainUser(final String username, final String domain, final String password) {
return this.logonDomainUserEx(username, domain, password, WinBase.LOGON32_LOGON_NETWORK,
WinBase.LOGON32_PROVIDER_DEFAULT);
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#logonDomainUserEx(java.lang.String, java.lang.String,
* java.lang.String, int, int)
*/
@Override
public IWindowsIdentity logonDomainUserEx(final String username, final String domain, final String password,
final int logonType, final int logonProvider) {
final HANDLEByReference phUser = new HANDLEByReference();
if (!Advapi32.INSTANCE.LogonUser(username, domain, password, logonType, logonProvider, phUser)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return new WindowsIdentityImpl(phUser.getValue());
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#logonUser(java.lang.String, java.lang.String)
*/
@Override
public IWindowsIdentity logonUser(final String username, final String password) {
// username@domain UPN format is natively supported by the
// Windows LogonUser API process domain\\username format
final String[] userNameDomain = username.split("\\\\", 2);
if (userNameDomain.length == 2) {
return this.logonDomainUser(userNameDomain[1], userNameDomain[0], password);
}
return this.logonDomainUser(username, null, password);
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#lookupAccount(java.lang.String)
*/
@Override
public IWindowsAccount lookupAccount(final String username) {
return new WindowsAccountImpl(username);
}
/*
* (non-Javadoc)
* @see waffle.windows.auth.IWindowsAuthProvider#resetSecurityToken(java.lang.String)
*/
@Override
public void resetSecurityToken(final String connectionId) {
this.continueContexts.asMap().remove(connectionId);
}
/**
* Number of elements in the continue contexts map.
*
* @return Number of elements in the hash map.
*/
public int getContinueContextsSize() {
return this.continueContexts.asMap().size();
}
}
|
package com.denis.home.sunnynotes.noteDetail;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.denis.home.sunnynotes.BuildConfig;
import com.denis.home.sunnynotes.CustomApplication;
import com.denis.home.sunnynotes.R;
import com.denis.home.sunnynotes.Utility;
import com.denis.home.sunnynotes.data.NoteColumns;
import com.denis.home.sunnynotes.dropbox.DropboxFragment;
import com.denis.home.sunnynotes.service.ActionServiceHelper;
import com.dropbox.core.android.Auth;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import timber.log.Timber;
/**
* A simple {@link Fragment} subclass.
* Use the {@link NoteDetailFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class NoteDetailFragment extends DropboxFragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static final String DETAIL_URI = "URI";
private static final int DETAIL_LOADER = 0;
private static final String SUNNY_NOTES_SHARE_HASHTAG = " #SunnyNotes";
private Uri mUri;
private String mShareNote;
private EditText mNoteTitleView;
private EditText mNoteContentView;
private boolean isAddMode = false;
private android.support.v7.app.ActionBar mActionBar;
private Tracker mTracker;
public NoteDetailFragment() {
// Required empty public constructor
setHasOptionsMenu(true);
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param noteUri content uri .
* @return A new instance of fragment NoteDetailFragment.
*/
public static NoteDetailFragment newInstance(Uri noteUri) {
NoteDetailFragment fragment = new NoteDetailFragment();
Bundle args = new Bundle();
args.putParcelable(DETAIL_URI, noteUri);
fragment.setArguments(args);
return fragment;
}
private void finishCreatingMenu(Menu menu) {
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share_note);
menuItem.setIntent(createShareForecastIntent());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (getActivity() instanceof NoteDetailActivity) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detail, menu);
finishCreatingMenu(menu);
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mShareNote + SUNNY_NOTES_SHARE_HASHTAG);
return shareIntent;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_delete_note) {
if (mUri != null) {
if (hasToken()) {
// Check internet
if (Utility.isNetworkAvailable(getActivity())) {
Utility.deleteTxtFile(getActivity(), mUri);
ActionServiceHelper.Delete(getActivity(), mUri);
getActivity().finish();
} else {
Toast.makeText(getActivity(),
getString(R.string.note_detail_no_network),
Toast.LENGTH_SHORT).
show();
}
} else {
Auth.startOAuth2Authentication(getActivity(), BuildConfig.DROPBOX_APP_KEY_JAVA);
}
} else {
Toast.makeText(getActivity(),
getString(R.string.note_detail_note_dont_created),
Toast.LENGTH_SHORT).
show();
}
return true;
} else if (id == R.id.action_save_note) {
if (mUri != null) {
String filename = mNoteTitleView.getText().toString();
String content = mNoteContentView.getText().toString();
if (hasToken()) {
if (Utility.isValidNoteTitle(filename)) {
if (!Utility.getNoteIdIfExist(getActivity(), filename, mUri)) {
// Check internet
if (Utility.isNetworkAvailable(getActivity())) {
Utility.updateTxtFile(getActivity(), mUri, content);
ActionServiceHelper.Update(getActivity(), mUri, filename);
} else {
Toast.makeText(getActivity(),
getString(R.string.note_detail_no_network),
Toast.LENGTH_SHORT).
show();
}
} else {
mNoteTitleView.setError(getString(R.string.error_note_exist));
}
} else {
mNoteTitleView.setError(getString(R.string.error_invalid_note_title));
}
} else {
Auth.startOAuth2Authentication(getActivity(), BuildConfig.DROPBOX_APP_KEY_JAVA);
}
} else {
String filename = mNoteTitleView.getText().toString();
String content = mNoteContentView.getText().toString();
if (hasToken()) {
if (Utility.isValidNoteTitle(filename)) {
if (!Utility.getNoteIdIfExist(getActivity(), filename)) {
// Check internet
if (Utility.isNetworkAvailable(getActivity())) {
filename = mNoteTitleView.getText().toString();
content = mNoteContentView.getText().toString();
String filePath = Utility.createTxtFile(getActivity(), filename, content);
ActionServiceHelper.Add(getActivity(), filePath);
} else {
Toast.makeText(getActivity(),
getString(R.string.note_detail_no_network),
Toast.LENGTH_SHORT).
show();
}
} else {
mNoteTitleView.setError(getString(R.string.error_note_exist));
}
} else {
mNoteTitleView.setError(getString(R.string.error_invalid_note_title));
}
} else {
Auth.startOAuth2Authentication(getActivity(), BuildConfig.DROPBOX_APP_KEY_JAVA);
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUri = getArguments().getParcelable(DETAIL_URI);
if (mUri == null) {
isAddMode = true;
}
}
}
@Override
public void onResume() {
mTracker.setScreenName(getString(R.string.analytics_note_detail_page));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
super.onResume();
}
@Override
protected void loadData() {
}
@Override
protected void registrationInterruption() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_note_detail, container, false);
mNoteTitleView = (EditText) rootView.findViewById(R.id.note_title_edittext_view);
mNoteContentView = (EditText) rootView.findViewById(R.id.note_content_edittext_view);
mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
if (!isAddMode) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
}
CustomApplication application = (CustomApplication) getActivity().getApplication();
mTracker = application.getDefaultTracker();
super.onActivityCreated(savedInstanceState);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
String noteName = data.getString(data.getColumnIndex(NoteColumns.FILE_NAME));
noteName = Utility.stripDotTxtInString(noteName);
String lowerPath = data.getString(data.getColumnIndex(NoteColumns.LOWER_PATH));
String fileContent = Utility.readTxtFile(getActivity(), lowerPath);
Timber.d("Loader finesh, show note with title: " + noteName);
mNoteTitleView.setText(noteName);
mNoteContentView.setText(fileContent);
mShareNote = String.format("%s:\n%s", noteName, fileContent);
if (mActionBar != null) {
mActionBar.setTitle(noteName);
}
//mNoteTitleView.setText("Hi HI hI debug");
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (null != mUri) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity(),
mUri,
new String[]{NoteColumns.FILE_ID, NoteColumns.FILE_NAME, NoteColumns.DISPLAY_PATH, NoteColumns.LOWER_PATH},
null,
null,
null
);
}
return null;
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
|
package com.github.aldurd392.UnitedTweetsAnalyzer;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Evaluation;
import weka.classifiers.UpdateableClassifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.bayes.NaiveBayesUpdateable;
import weka.classifiers.functions.LibSVM;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.classifiers.functions.SMO;
import weka.classifiers.lazy.KStar;
import weka.classifiers.meta.AdaBoostM1;
import weka.classifiers.rules.PART;
import weka.classifiers.trees.*;
import weka.core.*;
import weka.core.stopwords.StopwordsHandler;
import weka.experiment.InstanceQuery;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToString;
import weka.filters.unsupervised.attribute.NumericToNominal;
import weka.filters.unsupervised.attribute.Remove;
import weka.filters.unsupervised.attribute.StringToWordVector;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Pattern;
/**
* Dynamically load and configure a Machine Learner based on a name.
* Train it and evaluate the obtained results,
* or classify unknown instances.
*/
class Learner {
private final static Logger logger = LogManager.getLogger(Learner.class.getSimpleName());
private final static String LOCATION_PREFIX = "_LOCATION";
/**
* This map will let you add other classifiers to this class.
* You can specify all those classifiers that inherit from AbstractClassifier
*
* @see AbstractClassifier
*/
public final static Map<String, Class<? extends AbstractClassifier>> classifiers;
static {
HashMap<String, Class<? extends AbstractClassifier>> map = new HashMap<>();
map.put("nbayes", NaiveBayesUpdateable.class);
map.put("dtree", J48.class);
map.put("reptree", REPTree.class);
map.put("htree", HoeffdingTree.class);
map.put("part", PART.class);
map.put("random_tree", RandomTree.class);
map.put("random_forest", RandomForest.class);
map.put("decision_stump", DecisionStump.class);
map.put("perceptron", MultilayerPerceptron.class);
map.put("libsvm", LibSVM.class);
map.put("smo", SMO.class); // LibSVM is faster.
map.put("kstar", KStar.class);
map.put("adaboost", AdaBoostM1.class);
classifiers = Collections.unmodifiableMap(map);
}
private static final char CSV_DELIMITER = ';';
private static final Object[] CSV_FILE_HEADER = {
"id", "profile_url", "location", "lang", "utc_offset", "timezone", "country",
};
/**
* We use this regex to split the command line into
* a vector of Strings.
* We compile it for performance reason.
*/
private final static Pattern re_spaces = Pattern.compile("\\s+");
/**
* We'll keep the instances used for training here.
*/
private Instances training_data = null;
/**
* We'll keep the unlabeled instances here.
*/
private Instances classification_data = null;
/**
* We'll keep the classifier here.
*/
private AbstractClassifier classifier = null;
/**
* Build a new learner
*
* @param classifier_name the name of the classifier used by the learner.
* @param cl_config Weka command line configuration for the learner.
* @throws Exception on error.
*/
public Learner(String classifier_name, String cl_config) throws Exception {
super();
this.classifierFactory(classifier_name, cl_config);
}
public Instances getTrainingData() {
return this.training_data;
}
public AbstractClassifier getClassifier() {
return this.classifier;
}
/**
* Set up the instances in input, setting up the class attribute
* and if specified it apply the input filter.
*
* @param instances to set up.
* @param filters if set applies the filters on the input instances
* (in order).
* @return the set up instances.
*/
private Instances setUpData(Instances instances, Filter[] filters) {
Instances newInstances = instances;
if (filters != null) {
for (Filter filter : filters) {
try {
filter.setInputFormat(newInstances);
newInstances = Filter.useFilter(newInstances, filter);
} catch (Exception e) {
logger.warn(
"Cannot apply specified filter {}. Ignoring it.", filter.toString(),
e
);
}
}
}
newInstances.setClass(newInstances.attribute(Storage.COUNTRY));
return newInstances;
}
/**
* Load data from the DB and store them in instance variables.
* Note that we always randomize the order of the retrieved instances.
* <p>
* When we want to classify unlabeled instances, we have to make sure that
* the classifier knows the entire universe of attribute's values.
* Because of this, we load with a single query all the data we needs,
* and the we spit them.
* In this way the headers of the Instances set will contain the correct
* information.
* In addition, we convert the "location" attribute to a vector of words.
* It is nominal in our dataset, so we convert it to a string and then we
* split it.
*
* @param isTraining if set we are loading training instances.
* Otherwise, we're loading both training and unlabeled instances.
* @throws Exception on error.
*/
private void loadData(boolean isTraining) throws Exception {
logger.info("Loading {} data.", isTraining ? "training" : "training and unlabeled");
InstanceQuery query = null;
try {
query = new InstanceQuery();
NominalToString nomToStringFilter = new NominalToString();
StringToWordVector stringFilter = new StringToWordVector();
NumericToNominal numericToNominal = new NumericToNominal();
stringFilter.setDoNotOperateOnPerClassBasis(true);
stringFilter.setOutputWordCounts(false);
final int wordsToKeep = 100;
stringFilter.setWordsToKeep(wordsToKeep);
// stringFilter.setIDFTransform(true);
// stringFilter.setTFTransform(true);
stringFilter.setStemmer(null);
stringFilter.setAttributeNamePrefix(LOCATION_PREFIX);
/**
* Remove from the WordVector all those words with length 1.
*/
stringFilter.setStopwordsHandler(new StopwordsHandler() {
@Override
public boolean isStopword(String word) {
return word.length() <= 1;
}
});
Filter[] filters = {nomToStringFilter, stringFilter, numericToNominal};
String locationAttributeString;
if (isTraining) {
query.setQuery(Storage.TRAINING_QUERY);
Instances instances = query.retrieveInstances();
locationAttributeString = String.format(
"%d", instances.attribute(Storage.LOCATION).index() + 1
);
nomToStringFilter.setAttributeIndexes(
locationAttributeString
);
stringFilter.setAttributeIndices(
locationAttributeString
);
this.training_data = setUpData(instances, filters);
this.training_data.randomize(new Random());
assert (this.training_data.numAttributes() > 3 + wordsToKeep) :
"StringToWordVector doesn't seem to be working!";
for (Attribute attribute : Collections.list(this.training_data.enumerateAttributes())) {
logger.debug(attribute.name());
logger.debug(attribute.type());
}
logger.debug(this.training_data.classAttribute().name());
} else {
query.setQuery(Storage.CLASSIFICATION_QUERY);
Instances universe = query.retrieveInstances();
locationAttributeString = String.format(
"%d", universe.attribute(Storage.LOCATION).index() + 1
);
nomToStringFilter.setAttributeIndexes(
locationAttributeString
);
stringFilter.setAttributeIndices(
locationAttributeString
);
/**
* Load the whole universe of data:
* training and unlabeled.
*/
universe = setUpData(universe, filters);
assert (universe.attribute(Storage.UTC_OFFSET).type() == 1) : "Got bad types from database";
this.training_data = new Instances(universe, universe.numInstances() - 200);
this.classification_data = new Instances(universe, 200);
final Attribute class_attribute = universe.classAttribute();
/**
* Split the data in training and unlabeled.
* We could use a filter, but this is more efficient in main memory.
*/
for (int i = universe.numInstances() - 1; i >= 0; i
Instance instance = universe.instance(i);
universe.delete(i);
if (Utils.isMissingValue(instance.value(class_attribute))) {
this.classification_data.add(instance);
} else {
this.training_data.add(instance);
}
}
assert (this.classification_data.numInstances() <= Constants.classification_limit) :
"Bad number of classification data (" +
this.classification_data.numInstances() +
"), filter is likely to be not working.";
assert this.training_data.equalHeadersMsg(this.classification_data) == null :
"Bad instances headers: " + this.training_data.equalHeadersMsg(this.classification_data);
/**
* Remove the ID from the training data.
*/
Remove remove = new Remove();
remove.setAttributeIndices(String.format("%d", this.training_data.attribute(Storage.ID).index() + 1));
remove.setInputFormat(this.training_data);
this.training_data = Filter.useFilter(this.training_data, remove);
this.training_data.randomize(new Random());
assert this.training_data.numAttributes() == this.classification_data.numAttributes() - 1 :
"Training data filtering is not working, bad number of attributes.";
assert this.training_data.attribute(Storage.ID) == null :
"ID attributes can still be found after filtering!";
}
} catch (Exception e) {
logger.error("Error while executing DB query", e);
throw e;
} finally {
if (query != null) {
query.close();
}
}
}
/**
* Setup the classifier parameters'.
*/
private void setupLearner() {
logger.info("Applying default configuration to {}", this.classifier.getClass().getSimpleName());
if (this.classifier instanceof J48) {
J48 j48 = (J48) this.classifier;
j48.setCollapseTree(false);
j48.setBinarySplits(false);
j48.setUnpruned(false);
j48.setReducedErrorPruning(false);
j48.setConfidenceFactor(0.25f);
j48.setUseLaplace(true);
j48.setNumFolds(5);
j48.setSubtreeRaising(false);
} else if (this.classifier instanceof LibSVM) {
LibSVM libSVM = (LibSVM) this.classifier;
libSVM.setCacheSize(512);
libSVM.setNormalize(true);
libSVM.setShrinking(true);
libSVM.setKernelType(new SelectedTag(LibSVM.KERNELTYPE_POLYNOMIAL, LibSVM.TAGS_KERNELTYPE));
libSVM.setDegree(3);
libSVM.setSVMType(new SelectedTag(LibSVM.SVMTYPE_C_SVC, LibSVM.TAGS_SVMTYPE));
} else if (this.classifier instanceof NaiveBayes) {
NaiveBayes naiveBayes = (NaiveBayes) this.classifier;
// Configure NaiveBayes
naiveBayes.setUseKernelEstimator(false);
naiveBayes.setUseSupervisedDiscretization(false);
} else if (this.classifier instanceof RandomForest) {
RandomForest rndForest = (RandomForest) this.classifier;
// Configure RandomForest
rndForest.setNumExecutionSlots(5);
rndForest.setNumTrees(50);
rndForest.setMaxDepth(3);
} else if (this.classifier instanceof MultilayerPerceptron) {
MultilayerPerceptron perceptron = (MultilayerPerceptron) this.classifier;
// Configure perceptron
perceptron.setAutoBuild(true);
perceptron.setTrainingTime(250); // epochs
perceptron.setNominalToBinaryFilter(false);
perceptron.setNormalizeAttributes(true);
}
}
/**
* Instantiate a classifier from it's name.
*
* @param classifier_name the name of the classifier to be instantiated.
* @param cl_config Weka configuration for the learner.
* This overrides the setup in {@link #setupLearner()}.
* @throws Exception on instantiation error.
*/
private void classifierFactory(String classifier_name, String cl_config) throws Exception {
Class<? extends AbstractClassifier> classifier_class = Learner.classifiers.get(classifier_name);
if (classifier_class == null) {
final String error = "Unknown classifier name " + classifier_name;
logger.error(error);
throw new Exception(error);
}
try {
Constructor<? extends AbstractClassifier> constructor = classifier_class.getConstructor();
AbstractClassifier abstractClassifier = constructor.newInstance();
this.classifier = abstractClassifier;
setupLearner();
if (cl_config != null) {
/**
* Set the command line options.
*/
abstractClassifier.setOptions(re_spaces.split(cl_config));
}
} catch (NoSuchMethodException |
InvocationTargetException |
InstantiationException |
IllegalAccessException e) {
logger.error("Error while instantiating classifier {}", classifier_class.getSimpleName(), e);
throw e;
}
logger.debug("Classifier {} correctly created.", this.classifier.getClass().getSimpleName());
}
/**
* If evaluating by using a percentage of the dataset as test,
* this function split the data as required.
*
* @param percentage_split parameter indicating the percentage of test data.
* @return An entry containing, in order, training and test sets.
*/
private Map.Entry<Instances, Instances> splitTrainingTestData(float percentage_split) {
assert (percentage_split > 0 && percentage_split < 1);
final int trainingSize = (int) Math.round(this.training_data.numInstances() * (1.0 - percentage_split));
final int testingSize = this.training_data.numInstances() - trainingSize;
final Instances train = new Instances(this.training_data, 0, trainingSize);
final Instances test = new Instances(this.training_data, trainingSize, testingSize);
return new AbstractMap.SimpleEntry<>(train, test);
}
/**
* Train the classifier on the given instances.
*
* @param training_data the instances to use.
* @throws Exception if the classifier encounters and error while being built.
*/
private void trainClassifier(Instances training_data) throws Exception {
if (this.classifier instanceof UpdateableClassifier) {
logger.info("Building updateable classifier.");
UpdateableClassifier classifier = (UpdateableClassifier) this.classifier;
/**
* We always have to call @{@link AbstractClassifier#buildClassifier(Instances)}.
* We thus build a new Instances set from the dataset.
* Then, we start feeding the classifier.
*/
this.classifier.buildClassifier(new Instances(training_data, 0));
for (int i = training_data.numInstances() - 1; i >= 0; i
Instance instance = training_data.instance(i);
training_data.delete(i);
classifier.updateClassifier(instance);
}
} else {
this.classifier.buildClassifier(training_data);
}
}
/**
* Classify unseen instances.
* It builds the classifier against the training set
* and then assign a classification to each unlabeled instance.
*
* @param output_path optional path to store a CSV file with the results.
*/
public void buildAndClassify(String output_path) {
try {
this.loadData(false);
} catch (Exception e) {
logger.fatal("Error while loading training and unlabeled data", e);
return;
}
CSVPrinter csvFilePrinter = null;
FileWriter fileWriter = null;
if (output_path != null) {
final CSVFormat csvFileFormat = CSVFormat.EXCEL.withDelimiter(CSV_DELIMITER);
try {
fileWriter = new FileWriter(output_path);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(CSV_FILE_HEADER);
} catch (IOException e) {
logger.warn("Error while creating CSV file printer", e);
IOUtils.closeQuietly(fileWriter);
IOUtils.closeQuietly(csvFilePrinter);
}
}
try {
logger.info("Building classifier {}...",
this.classifier.getClass().getSimpleName());
this.trainClassifier(this.training_data);
} catch (Exception e) {
logger.fatal("Error while building classifier for new instances.", e);
IOUtils.closeQuietly(fileWriter);
IOUtils.closeQuietly(csvFilePrinter);
return;
}
final Attribute attribute_id = this.classification_data.attribute(Storage.ID);
final Attribute attribute_lang = this.classification_data.attribute(Storage.LANG);
final Attribute attribute_utc_offset = this.classification_data.attribute(Storage.UTC_OFFSET);
final Attribute attribute_timezone = this.classification_data.attribute(Storage.TIMEZONE);
Remove remove;
try {
remove = new Remove();
remove.setAttributeIndices(String.format("%d", attribute_id.index() + 1));
remove.setInputFormat(this.classification_data);
} catch (Exception e) {
logger.error("Error while building remove filter for unlabeled instances", e);
return;
}
for (Instance i : this.classification_data) {
remove.input(i);
Instance trimmedInstance = remove.output();
final long id = Double.valueOf(i.value(attribute_id)).longValue();
double classification;
try {
classification = this.classifier.classifyInstance(trimmedInstance);
} catch (Exception e) {
logger.warn("Classification - id: {}, class: UNAVAILABLE",
id
);
logger.error("Error while classifying unlabeled instance", e);
return;
}
StringBuilder location = new StringBuilder();
for (Attribute attribute : Collections.list(i.enumerateAttributes())) {
if (attribute.name().startsWith(LOCATION_PREFIX) &&
i.value(attribute) > 0) {
location.append(attribute.name().substring(LOCATION_PREFIX.length()));
location.append(" ");
}
}
final Object[] values = {
id,
String.format(Constants.twitter_user_intent, id),
location.toString(),
i.stringValue(attribute_lang),
i.stringValue(attribute_utc_offset),
i.stringValue(attribute_timezone),
this.training_data.classAttribute().value((int) classification),
};
logger.debug("Classification - {} -> {}", i.toString(), values[6]);
if (csvFilePrinter != null) {
try {
csvFilePrinter.printRecord(values);
} catch (IOException e) {
logger.error("Error while printing CSV records for ID {}", id, e);
}
}
}
IOUtils.closeQuietly(fileWriter);
IOUtils.closeQuietly(csvFilePrinter);
}
/**
* Build the classifier against the training data and evaluate it.
*
* @param evaluation_rate parameter specifying the evaluation type.
* If 0 < evaluation_rate < 1,
* we'll use evaluation_rate percentage of the
* dataset as test.
* Otherwise, we'll use evaluation_rate-fold-validation.
* @return the evaluation of the classifier.
*/
public Evaluation buildAndEvaluate(float evaluation_rate) {
try {
this.loadData(true);
} catch (Exception e) {
logger.error("Error while loading training data.", e);
return null;
}
Evaluation eval = null;
assert evaluation_rate > 0;
try {
if (evaluation_rate < 1) {
logger.info("Building and evaluating classifier {} with testing percentage {}...",
this.classifier.getClass().getSimpleName(), evaluation_rate);
Map.Entry<Instances, Instances> data = splitTrainingTestData(evaluation_rate);
this.trainClassifier(data.getKey());
eval = new Evaluation(data.getKey());
eval.evaluateModel(this.classifier, data.getValue());
} else {
eval = new Evaluation(this.training_data);
int rounded_evaluation_rate = Math.round(evaluation_rate);
logger.info("Building and evaluating classifier {} with {}-fold validation...",
this.classifier.getClass().getSimpleName(),
rounded_evaluation_rate);
eval.crossValidateModel(
this.classifier,
this.training_data,
rounded_evaluation_rate,
new Random()
);
}
} catch (Exception e) {
logger.error("Error while evaluating the classifier", e);
}
return eval;
}
}
|
package com.krishagni.catissueplus.rest.controller;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.krishagni.catissueplus.core.administrative.events.SiteSummary;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolSummary;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierDetail;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp.OP;
import com.krishagni.catissueplus.core.biospecimen.events.CopyCpOpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpQueryCriteria;
import com.krishagni.catissueplus.core.biospecimen.events.CpReportSettingsDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail;
import com.krishagni.catissueplus.core.biospecimen.events.FileDetail;
import com.krishagni.catissueplus.core.biospecimen.events.MergeCpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.WorkflowDetail;
import com.krishagni.catissueplus.core.biospecimen.repository.CpListCriteria;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService;
import com.krishagni.catissueplus.core.common.errors.CommonErrorCode;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityResp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.EntityDeleteResp;
import com.krishagni.catissueplus.core.common.events.Operation;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.Resource;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.de.events.FormSummary;
import com.krishagni.catissueplus.core.de.services.FormService;
import com.krishagni.catissueplus.core.query.Column;
import com.krishagni.catissueplus.core.query.ListConfig;
import com.krishagni.catissueplus.core.query.ListDetail;
import com.krishagni.catissueplus.core.query.ListGenerator;
import edu.common.dynamicextensions.nutility.IoUtil;
@Controller
@RequestMapping("/collection-protocols")
public class CollectionProtocolsController {
@Autowired
private CollectionProtocolService cpSvc;
@Autowired
private FormService formSvc;
@Autowired
private ListGenerator listGenerator;
@Autowired
private HttpServletRequest httpServletRequest;
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<CollectionProtocolSummary> getCollectionProtocols(
@RequestParam(value = "query", required = false)
String searchStr,
@RequestParam(value = "title", required = false)
String title,
@RequestParam(value = "irbId", required = false)
String irbId,
@RequestParam(value = "piId", required = false)
Long piId,
@RequestParam(value = "repositoryName", required = false)
String repositoryName,
@RequestParam(value = "instituteId", required = false)
Long instituteId,
@RequestParam(value = "startAt", required = false, defaultValue = "0")
int startAt,
@RequestParam(value = "maxResults", required = false, defaultValue = "100")
int maxResults,
@RequestParam(value = "detailedList", required = false, defaultValue = "false")
boolean detailedList) {
CpListCriteria crit = new CpListCriteria()
.query(searchStr)
.title(title)
.irbId(irbId)
.piId(piId)
.repositoryName(repositoryName)
.instituteId(instituteId)
.includePi(detailedList)
.includeStat(detailedList)
.startAt(startAt)
.maxResults(maxResults);
ResponseEvent<List<CollectionProtocolSummary>> resp = cpSvc.getProtocols(request(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/count")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Long> getCollectionProtocolsCount(
@RequestParam(value = "query", required = false)
String searchStr,
@RequestParam(value = "title", required = false)
String title,
@RequestParam(value = "irbId", required = false)
String irbId,
@RequestParam(value = "piId", required = false)
Long piId,
@RequestParam(value = "repositoryName", required = false)
String repositoryName,
@RequestParam(value = "instituteId", required = false)
Long instituteId) {
CpListCriteria crit = new CpListCriteria()
.query(searchStr)
.title(title)
.irbId(irbId)
.piId(piId)
.repositoryName(repositoryName)
.instituteId(instituteId);
ResponseEvent<Long> resp = cpSvc.getProtocolsCount(request(crit));
resp.throwErrorIfUnsuccessful();
return Collections.singletonMap("count", resp.getPayload());
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail getCollectionProtocol(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.getCollectionProtocol(request(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}/sites")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<SiteSummary> getSites(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
ResponseEvent<List<SiteSummary>> resp = cpSvc.getSites(request(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}/definition")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void getCpDefFile(
@PathVariable("id")
Long cpId,
@RequestParam(value = "includeIds", required = false, defaultValue = "false")
boolean includeIds,
HttpServletResponse httpResp)
throws JsonProcessingException {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
crit.setFullObject(true);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.getCollectionProtocol(request(crit));
resp.throwErrorIfUnsuccessful();
CollectionProtocolDetail cp = resp.getPayload();
cp.setSopDocumentName(null);
cp.setSopDocumentUrl(null);
SimpleFilterProvider filters = new SimpleFilterProvider();
if (includeIds) {
filters.addFilter("withoutId", SimpleBeanPropertyFilter.serializeAllExcept());
} else {
filters.addFilter("withoutId", SimpleBeanPropertyFilter.serializeAllExcept("id", "statementId"));
}
ObjectMapper mapper = new ObjectMapper();
String def = mapper.writer(filters).withDefaultPrettyPrinter().writeValueAsString(cp);
httpResp.setContentType("application/json");
httpResp.setHeader("Content-Disposition", "attachment;filename=CpDef_" + cpId + ".json");
InputStream in = null;
try {
in = new ByteArrayInputStream(def.getBytes());
IoUtil.copy(in, httpResp.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Error sending file", e);
} finally {
IoUtil.close(in);
}
}
@RequestMapping(method = RequestMethod.POST, value="/definition")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail importCpDef(@PathVariable("file") MultipartFile file)
throws IOException {
CollectionProtocolDetail cp = new ObjectMapper().readValue(file.getBytes(), CollectionProtocolDetail.class);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.importCollectionProtocol(new RequestEvent<>(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/sop-document")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void downloadSopDocument(@PathVariable("id") Long cpId, HttpServletResponse httpResp)
throws IOException {
ResponseEvent<File> resp = cpSvc.getSopDocument(request(cpId));
resp.throwErrorIfUnsuccessful();
File file = resp.getPayload();
String fileName = file.getName().split("_", 2)[1];
Utility.sendToClient(httpResp, fileName, file);
}
@RequestMapping(method = RequestMethod.POST, value="/sop-documents")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public String uploadSopDocument(@PathVariable("file") MultipartFile file)
throws IOException {
InputStream in = null;
try {
in = file.getInputStream();
FileDetail detail = new FileDetail();
detail.setFilename(file.getOriginalFilename());
detail.setFileIn(in);
ResponseEvent<String> resp = cpSvc.uploadSopDocument(request(detail));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
} finally {
IOUtils.closeQuietly(in);
}
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail createCollectionProtocol(@RequestBody CollectionProtocolDetail cp) {
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.createCollectionProtocol(request(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail updateCollectionProtocol(@RequestBody CollectionProtocolDetail cp) {
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.updateCollectionProtocol(request(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value="/{cpId}/copy")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail copyCollectionProtocol(
@PathVariable("cpId")
Long cpId,
@RequestBody
CollectionProtocolDetail cpDetail) {
CopyCpOpDetail opDetail = new CopyCpOpDetail();
opDetail.setCpId(cpId);
opDetail.setCp(cpDetail);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.copyCollectionProtocol(request(opDetail));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.PUT, value = "/{id}/consents-waived")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public CollectionProtocolDetail updateConsentsWaived(@PathVariable Long id, @RequestBody Map<String, String> props) {
CollectionProtocolDetail cp = new CollectionProtocolDetail();
cp.setId(id);
cp.setConsentsWaived(Boolean.valueOf(props.get("consentsWaived")));
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.updateConsentsWaived(request(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/dependent-entities")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<DependentEntityDetail> getCpDependentEntities(@PathVariable Long id) {
ResponseEvent<List<DependentEntityDetail>> resp = cpSvc.getCpDependentEntities(request(id));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.DELETE, value="/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public EntityDeleteResp<CollectionProtocolDetail> deleteCollectionProtocol(
@PathVariable
Long id,
@RequestParam(value = "forceDelete", required = false, defaultValue = "false")
boolean forceDelete,
@RequestParam(value = "reason", required = false, defaultValue = "")
String reason) {
BulkDeleteEntityOp crit = new BulkDeleteEntityOp();
crit.setIds(Collections.singleton(id));
crit.setForceDelete(forceDelete);
crit.setReason(reason);
ResponseEvent<BulkDeleteEntityResp<CollectionProtocolDetail>> resp = cpSvc.deleteCollectionProtocols(request(crit));
resp.throwErrorIfUnsuccessful();
BulkDeleteEntityResp<CollectionProtocolDetail> payload = resp.getPayload();
return new EntityDeleteResp<>(payload.getEntities().get(0), payload.isCompleted());
}
@RequestMapping(method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public BulkDeleteEntityResp<CollectionProtocolDetail> deleteCollectionProtocols(
@RequestParam(value = "id")
Long[] ids,
@RequestParam(value = "forceDelete", required = false, defaultValue = "false")
boolean forceDelete,
@RequestParam(value = "reason", required = false, defaultValue = "")
String reason) {
BulkDeleteEntityOp crit = new BulkDeleteEntityOp();
crit.setIds(new HashSet<>(Arrays.asList(ids)));
crit.setForceDelete(forceDelete);
crit.setReason(reason);
ResponseEvent<BulkDeleteEntityResp<CollectionProtocolDetail>> resp = cpSvc.deleteCollectionProtocols(request(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/consent-tiers")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<ConsentTierDetail> getConsentTiers(@PathVariable("id") Long cpId) {
ResponseEvent<List<ConsentTierDetail>> resp = cpSvc.getConsentTiers(request(cpId));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value="/{id}/consent-tiers")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail addConsentTier(@PathVariable("id") Long cpId, @RequestBody ConsentTierDetail consentTier) {
return performConsentTierOp(OP.ADD, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}/consent-tiers/{tierId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail updateConsentTier(
@PathVariable("id")
Long cpId,
@PathVariable("tierId")
Long tierId,
@RequestBody
ConsentTierDetail consentTier) {
consentTier.setId(tierId);
return performConsentTierOp(OP.UPDATE, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.DELETE, value="/{id}/consent-tiers/{tierId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail removeConsentTier(
@PathVariable("id")
Long cpId,
@PathVariable("tierId")
Long tierId) {
ConsentTierDetail consentTier = new ConsentTierDetail();
consentTier.setId(tierId);
return performConsentTierOp(OP.REMOVE, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/consent-tiers/{tierId}/dependent-entities")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<DependentEntityDetail> getConsentDependentEntities(
@PathVariable("id")
Long cpId,
@PathVariable("tierId")
Long tierId) {
ConsentTierDetail consentTierDetail = new ConsentTierDetail();
consentTierDetail.setCpId(cpId);
consentTierDetail.setId(tierId);
ResponseEvent<List<DependentEntityDetail>> resp = cpSvc.getConsentDependentEntities(request(consentTierDetail));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/barcoding-enabled")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Boolean isSpecimenBarcodingEnabled() {
ResponseEvent<Boolean> resp = cpSvc.isSpecimenBarcodingEnabled();
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/workflows")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail getWorkflowCfg(@PathVariable("id") Long cpId) {
ResponseEvent<CpWorkflowCfgDetail> resp = cpSvc.getWorkflows(new RequestEvent<>(cpId));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/workflows-file")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void getWorkflowCfg(@PathVariable("id") Long cpId, HttpServletResponse httpResp) {
ResponseEvent<CpWorkflowCfgDetail> resp = cpSvc.getWorkflows(new RequestEvent<>(cpId));
resp.throwErrorIfUnsuccessful();
InputStream in = null;
try {
CpWorkflowCfgDetail workflowDetail = resp.getPayload();
String filename = (workflowDetail.getShortTitle() + "_workflows.json")
.replaceAll("\\\\", "_") // replace backslash with _
.replaceAll("/", "_") // replace forward slash with _
.replaceAll("\\s+", "_"); // replace whitespace with _
String workflowsJson = new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(resp.getPayload().getWorkflows().values());
in = new ByteArrayInputStream(workflowsJson.getBytes());
Utility.sendToClient(httpResp, filename, "application/json", in);
} catch (Exception e) {
throw OpenSpecimenException.userError(CommonErrorCode.FILE_SEND_ERROR, e.getMessage());
} finally {
IOUtils.closeQuietly(in);
}
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}/workflows")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail saveWorkflowCfg(@PathVariable("id") Long cpId, @RequestBody List<WorkflowDetail> workflows) {
return saveWorkflows(cpId, workflows, false);
}
@RequestMapping(method = RequestMethod.POST, value="/{id}/workflows-file")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail saveWorkflowCfg(@PathVariable("id") Long cpId, @PathVariable("file") MultipartFile file) {
List<WorkflowDetail> workflows;
try {
ObjectMapper mapper = new ObjectMapper();
workflows = mapper.readValue(file.getInputStream(), new TypeReference<List<WorkflowDetail>>() {});
} catch (Exception e) {
throw OpenSpecimenException.userError(CommonErrorCode.INVALID_REQUEST, e.getMessage());
}
return saveWorkflows(cpId, workflows, false);
}
@RequestMapping(method = RequestMethod.PATCH, value="/{id}/workflows")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail patchWorkflowCfg(@PathVariable("id") Long cpId, @RequestBody List<WorkflowDetail> workflows) {
return saveWorkflows(cpId, workflows, true);
}
// Report settings API
@RequestMapping(method = RequestMethod.GET, value="/{id}/report-settings")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpReportSettingsDetail getReportSettings(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
RequestEvent<CpQueryCriteria> req = new RequestEvent<>(crit);
ResponseEvent<CpReportSettingsDetail> resp = cpSvc.getReportSettings(req);
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}/report-settings")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpReportSettingsDetail updateReportSettings(
@PathVariable("id")
Long cpId,
@RequestBody
CpReportSettingsDetail detail) {
CollectionProtocolSummary cp = new CollectionProtocolSummary();
cp.setId(cpId);
detail.setCp(cp);
RequestEvent<CpReportSettingsDetail> req = new RequestEvent<>(detail);
ResponseEvent<CpReportSettingsDetail> resp = cpSvc.saveReportSettings(req);
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.DELETE, value="/{id}/report-settings")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpReportSettingsDetail deleteReportSettings(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
RequestEvent<CpQueryCriteria> req = new RequestEvent<>(crit);
ResponseEvent<CpReportSettingsDetail> resp = cpSvc.deleteReportSettings(req);
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value = "/{id}/report")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Boolean> generateReport(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
ResponseEvent<Boolean> resp = cpSvc.generateReport(new RequestEvent<>(crit));
resp.throwErrorIfUnsuccessful();
return Collections.singletonMap("status", resp.getPayload());
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/report")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void downloadCpReport(
@PathVariable("id")
Long cpId,
@RequestParam(value = "fileId", required = true)
String fileId,
HttpServletResponse httpResp)
throws IOException {
ResponseEvent<File> resp = cpSvc.getReportFile(cpId, fileId);
resp.throwErrorIfUnsuccessful();
File file = resp.getPayload();
String extn = ".csv";
int extnStartIdx = file.getName().lastIndexOf('.');
if (extnStartIdx != -1) {
extn = file.getName().substring(extnStartIdx);
}
Utility.sendToClient(httpResp, "CpReport" + extn, file);
}
// For UI work
@RequestMapping(method = RequestMethod.GET, value="/byop")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<CollectionProtocolSummary> getCpListByOp(
@RequestParam(value = "resource", required = true)
String resourceName,
@RequestParam(value = "op", required = true)
String opName,
@RequestParam(value = "siteName", required = false)
String[] siteNames,
@RequestParam(value = "title", required = false)
String searchTitle,
@RequestParam(value = "maxResults", required = false, defaultValue = "100")
int maxResults) {
List<String> inputSiteList = Collections.emptyList();
if (siteNames != null) {
inputSiteList = Arrays.asList(siteNames);
}
Resource resource = Resource.fromName(resourceName);
Operation op = Operation.fromName(opName);
List<CollectionProtocolSummary> emptyList = Collections.<CollectionProtocolSummary>emptyList();
ResponseEvent<List<CollectionProtocolSummary>> resp = new ResponseEvent<List<CollectionProtocolSummary>>(emptyList);
if (resource == Resource.PARTICIPANT && op == Operation.CREATE) {
resp = cpSvc.getRegisterEnabledCps(inputSiteList, searchTitle, maxResults);
}
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/extension-form")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> getForm() {
return formSvc.getExtensionInfo(-1L, CollectionProtocol.EXTN);
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/forms")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<FormSummary> getForms(
@PathVariable("id")
Long cpId,
@RequestParam(value = "entityType", required = true)
String[] entityTypes) {
return formSvc.getEntityForms(cpId, entityTypes);
}
@RequestMapping(method = RequestMethod.POST, value="/merge")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public MergeCpDetail mergeCollectionProtocol(@RequestBody MergeCpDetail mergeDetail) {
ResponseEvent<MergeCpDetail> resp = cpSvc.mergeCollectionProtocols(request(mergeDetail));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}/list-config")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ListConfig getListConfig(
@PathVariable("id")
Long cpId,
@RequestParam(value = "listName", required = true)
String listName) {
Map<String, Object> listCfgReq = new HashMap<>();
listCfgReq.put("cpId", cpId);
listCfgReq.put("listName", listName);
ResponseEvent<ListConfig> resp = cpSvc.getCpListCfg(new RequestEvent<>(listCfgReq));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}/expression-values")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Collection<Object> getExpressionValues(
@PathVariable("id")
Long cpId,
@RequestParam(value = "listName")
String listName,
@RequestParam(value = "expr")
String expr,
@RequestParam(value = "searchTerm", required = false, defaultValue = "")
String searchTerm) {
Map<String, Object> listReq = new HashMap<>();
listReq.put("cpId", cpId);
listReq.put("listName", listName);
listReq.put("expr", expr);
listReq.put("searchTerm", searchTerm);
ResponseEvent<Collection<Object>> resp = cpSvc.getListExprValues(new RequestEvent<>(listReq));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value = "/{id}/list-detail")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ListDetail getListDetail(
@PathVariable("id")
Long cpId,
@RequestParam(value = "listName")
String listName,
@RequestParam(value = "startAt", required = false, defaultValue = "0")
int startAt,
@RequestParam(value = "maxResults", required = false, defaultValue = "100")
int maxResults,
@RequestParam(value = "includeCount", required = false, defaultValue = "false")
boolean includeCount,
@RequestBody
List<Column> filters) {
Map<String, Object> listReq = new HashMap<>();
listReq.put("cpId", cpId);
listReq.put("listName", listName);
listReq.put("startAt", startAt);
listReq.put("maxResults", maxResults);
listReq.put("includeCount", includeCount);
listReq.put("filters", filters);
ResponseEvent<ListDetail> resp = cpSvc.getList(request(listReq));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value = "/{id}/list-size")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Integer> getListSize(
@PathVariable("id")
Long cpId,
@RequestParam(value = "listName", required = true)
String listName,
@RequestBody
List<Column> filters) {
Map<String, Object> listReq = new HashMap<>();
listReq.put("cpId", cpId);
listReq.put("listName", listName);
listReq.put("filters", filters);
ResponseEvent<Integer> resp = cpSvc.getListSize(request(listReq));
resp.throwErrorIfUnsuccessful();
return Collections.singletonMap("size", resp.getPayload());
}
@RequestMapping(method = RequestMethod.POST, value = "/{id}/labels")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Boolean> addLabel(@PathVariable("id") Long cpId) {
return Collections.singletonMap("status", cpSvc.toggleStarredCp(cpId, true));
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}/labels")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Boolean> removeLabel(@PathVariable("id") Long cpId) {
return Collections.singletonMap("status", cpSvc.toggleStarredCp(cpId, false));
}
private ConsentTierDetail performConsentTierOp(OP op, Long cpId, ConsentTierDetail consentTier) {
ConsentTierOp req = new ConsentTierOp();
req.setConsentTier(consentTier);
req.setCpId(cpId);
req.setOp(op);
ResponseEvent<ConsentTierDetail> resp = cpSvc.updateConsentTier(request(req));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
private CpWorkflowCfgDetail saveWorkflows(Long cpId, List<WorkflowDetail> workflows, boolean patch) {
CpWorkflowCfgDetail input = new CpWorkflowCfgDetail();
input.setCpId(cpId);
input.setPatch(patch);
for (WorkflowDetail workflow : workflows) {
input.getWorkflows().put(workflow.getName(), workflow);
}
return response(cpSvc.saveWorkflows(request(input)));
}
private <T> RequestEvent<T> request(T payload) {
return new RequestEvent<>(payload);
}
private <T> T response(ResponseEvent<T> resp) {
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
}
|
package org.voovan.http.server.module.annontationRouter.swagger;
import org.voovan.Global;
import org.voovan.http.message.HttpStatic;
import org.voovan.http.server.*;
import org.voovan.http.server.module.annontationRouter.annotation.*;
import org.voovan.http.server.module.annontationRouter.router.AnnotationRouter;
import org.voovan.http.server.module.annontationRouter.router.RouterInfo;
import org.voovan.http.server.module.annontationRouter.swagger.annotation.ApiModel;
import org.voovan.http.server.module.annontationRouter.swagger.annotation.ApiProperty;
import org.voovan.http.server.module.annontationRouter.swagger.annotation.ApiGeneric;
import org.voovan.http.server.module.annontationRouter.swagger.entity.*;
import org.voovan.http.server.module.annontationRouter.swagger.entity.Properties;
import org.voovan.http.server.module.annontationRouter.swagger.entity.Schema;
import org.voovan.tools.TFile;
import org.voovan.tools.TObject;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import org.voovan.tools.reflect.annotation.NotSerialization;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class SwaggerApi {
public static ConcurrentHashMap<String,Swagger> MODULE_SWAGGER = new ConcurrentHashMap<String, Swagger>();
static {
}
public static void init(HttpModule httpModule) {
WebServer webserver = httpModule.getWebServer();
Map<String, Object> swaggerConfig = (Map<String, Object>) httpModule.getModuleConfig().getParameter("Swagger");
if(swaggerConfig == null) {
swaggerConfig = TObject.asMap();
}
String moduleName = httpModule.getModuleConfig().getName();
String modulePath = httpModule.getModuleConfig().getPath();
Boolean enable = (Boolean) swaggerConfig.getOrDefault("Enable", true);
if(enable == false) {
return;
}
String routePath = (String) swaggerConfig.getOrDefault("RoutePath", "/swagger");
Integer refreshInterval = (Integer) swaggerConfig.getOrDefault("RefreshInterval", -1);
String description = (String) swaggerConfig.getOrDefault("Description", "");
String version = (String) swaggerConfig.get("Version");
MODULE_SWAGGER.put(moduleName, new Swagger(httpModule.getModuleConfig().getPath(), description, version));
if(enable) {
SwaggerApi.buildModuleSwagger(moduleName);
if(refreshInterval > 0) {
Global.getHashWheelTimer().addTask(() -> {
MODULE_SWAGGER.put(moduleName, new Swagger(modulePath, description, version));
SwaggerApi.buildModuleSwagger(moduleName);
}, refreshInterval);
}
String swaggerPath = routePath + (modulePath.startsWith("/") ? modulePath : ("/" + modulePath));
swaggerPath = HttpDispatcher.fixRoutePath(swaggerPath);
webserver.get(swaggerPath+"-ui", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpStatic.TEXT_HTML_STRING);
String content = new String(TFile.loadResource("org/voovan/http/server/conf/swagger.html"));
content = content.replace("${Title}", moduleName + " - voovan" );
response.write(content);
}
});
webserver.get(swaggerPath, new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpStatic.APPLICATION_JSON_STRING);
response.write(JSON.removeNullNode(JSON.toJSON(MODULE_SWAGGER.get(moduleName))));
}
});
Logger.simplef("[SWAGGER] module: {1} path: {2}, refreshInterval: {3}", moduleName, swaggerPath, refreshInterval);
}
}
public static Swagger buildModuleSwagger(String moduleName) {
return buildSwagger(MODULE_SWAGGER.get(moduleName));
}
public static Swagger buildSwagger(Swagger swagger) {
swagger.getTags().addAll(parseAllTags());
Collections.sort(swagger.getTags(), Swagger.TAG_COMPARATOR);
Map<String, Tag> tagsMap = new HashMap<String, Tag>();
for(RouterInfo routerInfo : AnnotationRouter.ROUTER_INFO_LIST) {
String classUrl = routerInfo.getClassAnnotation().value() == null ? routerInfo.getClassAnnotation().path() : routerInfo.getClassAnnotation().value();
classUrl = HttpDispatcher.fixRoutePath(classUrl);
String url = routerInfo.getUrl();
// swagger
while(url.indexOf("/:") >0 ) {
int startIndex = url.indexOf(":");
url = url.substring(0, startIndex) + "{" + url.substring(startIndex + 1);
int endIndex = url.indexOf("/", startIndex + 1);
if(endIndex > 0) {
url = TString.insert(url, endIndex, "}");
} else {
url = url + "}";
}
}
url = HttpDispatcher.fixRoutePath(url);
String routeMethod = routerInfo.getRouteMethod();
Router classAnnotation = routerInfo.getClassAnnotation();
Class clazz = routerInfo.getClass();
Router methodAnnotation = routerInfo.getMethodAnnotation();
Method method = routerInfo.getMethod();
if(methodAnnotation.hide()) {
continue;
}
String operationId = routerInfo.getClazz().getSimpleName() + "." + routerInfo.getMethod().getName();
Path path = new Path(operationId, methodAnnotation.summary(), methodAnnotation.description(),
new String[]{HttpStatic.APPLICATION_JSON_STRING}, new String[]{HttpStatic.APPLICATION_JSON_STRING},
methodAnnotation.deprecated());
// Tag
path.getTags().addAll(TObject.asList(methodAnnotation.tags()));
for(Tag tag : parseTags(classAnnotation).values()) {
path.getTags().add(tag.getName());
}
path.getTags().add(classUrl);
Annotation[][] paramAnnotationsArrary = method.getParameterAnnotations();
Class[] paramTypes = method.getParameterTypes();
int unNamedParamCount = 1;
for (int i = 0; i < paramAnnotationsArrary.length; i++) {
Annotation[] paramAnnotations = paramAnnotationsArrary[i];
if (paramTypes[i] == HttpRequest.class ||
paramTypes[i] == HttpResponse.class ||
paramTypes[i] == HttpSession.class) {
continue;
}
if (paramAnnotations.length > 0) {
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof Param) {
Parameter parameter = new Parameter();
parameter.setIn("path");
String[] types = getParamType(paramTypes[i]);
parameter.setType(types[0]);
parameter.setFormat(types[1]);
parameter.setName(((Param) paramAnnotation).value());
parameter.setDescription(((Param) paramAnnotation).description());
parameter.setRequired(((Param) paramAnnotation).isRequire());
parameter.setDefaultVal(((Param) paramAnnotation).defaultVal());
parameter.setExample(((Param) paramAnnotation).example());
path.getParameters().add(parameter);
} else if (paramAnnotation instanceof Header) {
Parameter parameter = new Parameter();
parameter.setIn("header");
String[] types = getParamType(paramTypes[i]);
parameter.setType(types[0]);
parameter.setFormat(types[1]);
parameter.setName(((Header) paramAnnotation).value());
parameter.setDescription(((Header) paramAnnotation).description());
parameter.setRequired(((Header) paramAnnotation).isRequire());
parameter.setDefaultVal(((Header) paramAnnotation).defaultVal());
parameter.setExample(((Header) paramAnnotation).example());
path.getParameters().add(parameter);
} else if (paramAnnotation instanceof Cookie) {
Parameter parameter = new Parameter();
parameter.setIn("cookie");
String[] types = getParamType(paramTypes[i]);
parameter.setType(types[0]);
parameter.setFormat(types[1]);
parameter.setName(((Cookie) paramAnnotation).value());
parameter.setDescription(((Cookie) paramAnnotation).description());
parameter.setRequired(((Cookie) paramAnnotation).isRequire());
parameter.setDefaultVal(((Cookie) paramAnnotation).defaultVal());
parameter.setExample(((Cookie) paramAnnotation).example());
path.getParameters().add(parameter);
}else if (paramAnnotation instanceof BodyParam) {
if(path.getParameters().size() == 0) {
Parameter parameter = new Parameter();
parameter.setIn("body");
parameter.setName("body");
path.getParameters().add(parameter);
}
Parameter parameter = path.getParameters().get(0);
Schema schema = parameter.getSchema();
String name = ((BodyParam) paramAnnotation).value();
String description = ((BodyParam) paramAnnotation).description();
String defaultVal = ((BodyParam) paramAnnotation).defaultVal();
boolean isRequire = ((BodyParam) paramAnnotation).isRequire();
String example = ((BodyParam) paramAnnotation).example();
createSchema(swagger, parameter.getSchema(), paramTypes[i], name, description, defaultVal, isRequire, example, true);
if(method.getAnnotationsByType(ApiGeneric.class).length > 0) {
if (parameter.getSchema().getType().equals("object")) {
for (Schema propertySchema : parameter.getSchema().getProperties().values()) {
generic(swagger, propertySchema, propertySchema.getClazz(), method, name);
}
}
}
} else if(paramAnnotation instanceof Body) {
Parameter parameter = new Parameter();
parameter.setIn("body");
parameter.setName("body");
String description = ((Body) paramAnnotation).description();
String defaultVal = ((Body) paramAnnotation).defaultVal();
String example = ((Body) paramAnnotation).example();
parameter.setDescription(description);
parameter.setDefaultVal(defaultVal);
Schema schema = parameter.getSchema();
createSchema(swagger, parameter.getSchema(), paramTypes[i], null, null, null, true, example, true);
path.getParameters().add(parameter);
if(method.getAnnotationsByType(ApiGeneric.class).length > 0) {
generic(swagger, parameter.getSchema(), paramTypes[i], method, null);
if (parameter.getSchema().getType().equals("object")) {
for (Schema propertySchema : parameter.getSchema().getProperties().values()) {
generic(swagger, propertySchema, propertySchema.getClazz(), method, null);
}
}
}
}
}
} else {
Parameter parameter = new Parameter();
parameter.setIn("path");
String[] types = getParamType(paramTypes[i]);
parameter.setType(types[0]);
parameter.setFormat(types[1]);
parameter.setName("param" + unNamedParamCount);
parameter.setRequired(true);
path.getParameters().add(parameter);
unNamedParamCount++;
}
}
Response response = buildResponse(swagger, method);
path.getResponses().put("200", response);
swagger.getPaths().put(url, TObject.asMap(routeMethod.toLowerCase(), path));
}
return swagger;
}
/**
*
* @param swagger Swagger
* @param method
* @return Response
*/
public static Response buildResponse(Swagger swagger, Method method) {
Class returnType = method.getReturnType();
Response response = new Response();
createSchema(swagger, response.getSchema(), returnType, null, null, null, null, null, false);
Schema schema = response.getSchema();
generic(swagger, schema, returnType, method, "response");
if(response.getSchema().getRef() == null) {
String schemaDescription = response.getSchema().getDescription();
if (schemaDescription != null && !schemaDescription.isEmpty()) {
response.setDescription(response.getSchema().getDescription());
}
}
response.getSchema().setType(null);
response.getSchema().setDescription(null);
response.getSchema().setExample(null);
response.getSchema().setDefaultVal(null);
response.getSchema().setRequired(null);
return response;
}
public static void generic(Swagger swagger, Schema schema, Class clazz, Method method, String name) {
ApiGeneric[] apiGenerics = method.getAnnotationsByType(ApiGeneric.class);
for(ApiGeneric apiGeneric : apiGenerics) {
if(!apiGeneric.param().isEmpty() && !apiGeneric.param().equals(name)) {
continue;
}
Class[] genericClass = apiGeneric.clazz();
for(int i=0;i<genericClass.length;i++) {
if (clazz == Object.class) {
schema.setType("object");
createSchema(swagger, schema, genericClass[i], null, null, null, null, null, false);
} else if (TReflect.isImpByInterface(clazz, Collection.class)) {
schema.setType("array");
createSchema(swagger, schema.getItems(), genericClass[i], null, null, null, null, null, false);
schema = schema.getItems();
} else if (TReflect.isImpByInterface(clazz, Map.class)) {
schema.setType("object");
Schema keySchema = new Schema("string", null);
keySchema.setClazz(String.class);
schema.getProperties().put("key", keySchema);
Schema valueSchema = new Schema();
valueSchema.setClazz(genericClass[i]);
createSchema(swagger, valueSchema, genericClass[i], null, null, null, null, null, false);
schema.getProperties().put("value", valueSchema);
schema = valueSchema;
} else {
// , schema
if (schema.getRef() != null) {
createSchema(swagger, schema, clazz, null, null, null, null, null, false);
}
Schema fieldSchema = schema.getProperties().get(apiGeneric.property());
if(fieldSchema == null) {
break;
}
createSchema(swagger, fieldSchema, genericClass[i], null, null, null, null, null, false);
schema = fieldSchema;
}
name = name + "." + schema.getClazz().getSimpleName();
clazz = genericClass[i];
if(name.startsWith("response") && i!=0) {
schema.setDescription(null);
schema.setExample(null);
schema.setDefaultVal(null);
schema.setRequired(null);
}
}
}
}
public static Collection<Tag> parseAllTags() {
Map<String, Tag> tagsMap = new HashMap<String, Tag>();
for(RouterInfo routerInfo : AnnotationRouter.ROUTER_INFO_LIST) {
tagsMap.putAll(parseTags(routerInfo.getClassAnnotation()));
String classUrl = routerInfo.getClassAnnotation().value() == null ? routerInfo.getClassAnnotation().path() : routerInfo.getClassAnnotation().value();
classUrl = HttpDispatcher.fixRoutePath(classUrl);
tagsMap.put(classUrl, new Tag(classUrl, "Tag of Router class: " + routerInfo.getClazz().getSimpleName()));
}
return tagsMap.values();
}
public static Map<String, Tag> parseTags(Router router) {
Map<String, Tag> tagsMap = new HashMap<String, Tag>();
for(String tag : router.tags()) {
tag = tag.trim();
if (tag.length() > 0) {
int descStart = tag.indexOf("[");
int descEnd = tag.lastIndexOf("]");
String name = descStart > 0 ? tag.substring(0, descStart) : tag;
String description = descStart > 0 && descEnd > 0 && descEnd > descStart ? tag.substring(descStart + 1, descEnd) : "";
tagsMap.put(name, new Tag(name, description));
}
}
return tagsMap;
}
public static Schema createSchema(Swagger swagger, Schema schema, Class clazz, String name, String description, String defaultVal, Boolean required, String example, boolean ref){
if(schema == null) {
schema = new Schema();
}
if(TReflect.isSystemType(clazz)) {
if(name == null) {
String[] types = getParamType(clazz);
schema.setType(types[0]);
schema.setFormat(types[1]);
schema.setExample(example);
} else {
//for @BodyParam
String[] types = getParamType(clazz);
schema.setType("object");
Schema property = new Schema(types[0], types[1]);
property.setClazz(clazz);
property.setDefaultVal(TString.isNullOrEmpty(defaultVal) ? null : defaultVal);
property.setDescription(TString.isNullOrEmpty(description) ? null : description);
property.setExample(example);
schema.getProperties().put(name, property);
if(required == null || required) {
schema.getRequired().add(name);
}
}
} else {
schema.setType("object");
if(name == null) {
//for @BodyParam
createProperites(swagger, schema, clazz, ref);
schema.setExample(example);
ApiModel apiModel = (ApiModel) clazz.getAnnotation(ApiModel.class);
if (apiModel != null) {
schema.setDescription(apiModel.value());
}
} else {
Schema property = new Schema();
createProperites(swagger, property, clazz, ref);
schema.setExample(example);
ApiModel apiModel = (ApiModel) clazz.getAnnotation(ApiModel.class);
if (apiModel != null) {
schema.setDescription(apiModel.value());
}
if(required == null || required) {
schema.getRequired().add(name);
}
schema.getProperties().put(name, property);
}
}
schema.setClazz(clazz);
return schema;
}
public static Object convertExample(String example) {
if(JSON.isJSON(example)) {
return JSON.parse(example);
} else {
return example;
}
}
public static Properties createProperites(Swagger swagger, Properties properties, Class clazz, boolean ref) {
//find created Definition
Schema definitionSchema = null;
if(ref) {
definitionSchema = swagger.getDefinitions().get(clazz.getSimpleName());
if (definitionSchema != null) {
properties.setProperties(null);
properties.setRef(clazz.getSimpleName());
if(properties instanceof Schema) {
((Schema)properties).setClazz(clazz);
}
return properties;
}
}
for (Field field : TReflect.getFields(clazz)) {
if(field.getName().startsWith("this$")){
continue;
}
if(Modifier.isTransient(field.getModifiers()) ||
Modifier.isStatic(field.getModifiers()) ||
field.isAnnotationPresent(NotSerialization.class)) {
continue;
}
ApiProperty apiProperty = field.getAnnotation(ApiProperty.class);
if(apiProperty!=null && apiProperty.hidden()) {
continue;
}
String[] types = getParamType(field.getType());
Schema schema = null;
if(types[0] == null) {
schema = new Schema();
schema.setClazz(field.getType());
createProperites(swagger, schema, field.getType(), ref);
schema.setProperties(null);
schema.setRequired(null);
schema.setRef(field.getType().getSimpleName());
} else {
schema = new Schema(types[0], types[1]);
schema.setClazz(field.getType());
if(apiProperty!=null) {
schema.setDescription(apiProperty.value());
if(!apiProperty.isRequire()) {
properties.getParent().getRequired().add(field.getName());
}
schema.setExample(apiProperty.example());
} else {
properties.getParent().getRequired().add(field.getName());
}
}
properties.getProperties().put(field.getName(), schema);
}
//create definition
if(!swagger.getDefinitions().containsKey(clazz.getSimpleName())) {
definitionSchema = new Schema();
definitionSchema.setClazz(clazz);
definitionSchema.setType("object");
definitionSchema.getProperties().putAll(properties.getProperties());
swagger.getDefinitions().put(clazz.getSimpleName(), definitionSchema);
}
if(ref){
properties.setProperties(null);
properties.setRef(clazz.getSimpleName());
}
if(properties instanceof Schema) {
((Schema)properties).setClazz(clazz);
}
return properties;
}
public static String[] getParamType(Class clazz) {
if(TReflect.getUnPackageType(clazz.getSimpleName()).equals("String")) {
return new String[]{"string", null};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("int")) {
return new String[]{"integer", "int32"};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("long")) {
return new String[]{"integer", "int64"};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("float")) {
return new String[]{"number", "float"};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("double")) {
return new String[]{"number", "double"};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("String")) {
return new String[]{"string", null};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("byte")) {
return new String[]{"string", "byte"};
} else if(TReflect.getUnPackageType(clazz.getName()).equals("boolean")) {
return new String[]{"boolean", null};
} else if(TReflect.getUnPackageType(clazz.getSimpleName()).equals("Date")) {
return new String[]{"string", "date"};
} else if(TReflect.getUnPackageType(clazz.getSimpleName()).equals("BigDecimal")) {
return new String[]{"number", null};
} else if(clazz.isArray()) {
return new String[]{"array", clazz.getComponentType().getName().toLowerCase()};
} else if(TReflect.isImpByInterface(clazz, Collection.class)) {
Class[] classes = TReflect.getGenericClass(clazz);
return new String[]{"array", classes!=null ? getParamType(classes[0])[0] : null};
} else if(TReflect.isImpByInterface(clazz, Map.class)) {
return new String[]{"string", "object"};
} else if(clazz == Object.class) {
Class[] genericClazz = TReflect.getGenericClass(clazz);
return genericClazz!=null ? getParamType(genericClazz[0]) : new String[]{"object", null};
} else {
return new String[]{null, null};
}
}
}
|
package battlecode.world;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import battlecode.common.Direction;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.CommanderSkillType;
import battlecode.common.Team;
import battlecode.common.TerrainTile;
import battlecode.engine.GenericRobot;
import battlecode.engine.signal.Signal;
import battlecode.server.Config;
import battlecode.world.signal.AttackSignal;
import battlecode.world.signal.BashSignal;
import battlecode.world.signal.BroadcastSignal;
import battlecode.world.signal.DeathSignal;
import battlecode.world.signal.SelfDestructSignal;
import battlecode.world.signal.SpawnSignal;
import battlecode.world.signal.TransferSupplySignal;
public class InternalRobot extends InternalObject implements Robot, GenericRobot {
public final RobotType type;
protected volatile double myHealthLevel;
protected volatile double mySupplyLevel;
private double coreDelay;
private double weaponDelay;
private int missileCount;
protected volatile long controlBits;
int currentBytecodeLimit;
private volatile int bytecodesUsed;
protected volatile boolean hasBeenAttacked;
private boolean healthChanged;
private boolean missileCountChanged;
private boolean didSelfDestruct;
private boolean broadcasted;
private volatile HashMap<Integer, Integer> broadcastMap;
private int roundsAlive;
private ArrayList<Signal> supplyActions;
private ArrayList<SpawnSignal> missileLaunchActions;
private Signal movementSignal;
private Signal attackSignal;
private Signal castSignal;
private int buildDelay;
private static boolean upkeepEnabled = Config.getGlobalConfig().getBoolean("bc.engine.upkeep");
private int myBuilder, myBuilding;
private boolean forceDeath;
@SuppressWarnings("unchecked")
public InternalRobot(GameWorld gw, RobotType type, MapLocation loc, Team t,
boolean spawnedRobot, int buildDelay) {
super(gw, loc, t);
this.type = type;
this.buildDelay = buildDelay;
myHealthLevel = getMaxHealth();
if (type.isBuildable() && buildDelay > 0) {
myHealthLevel /= 2.0;
}
mySupplyLevel = 0.0;
coreDelay = 0.0;
weaponDelay = 0.0;
missileCount = 0;
controlBits = 0;
currentBytecodeLimit = type.bytecodeLimit;
bytecodesUsed = 0;
hasBeenAttacked = false;
healthChanged = true;
missileCountChanged = true;
didSelfDestruct = false;
broadcasted = false;
broadcastMap = new HashMap<Integer, Integer>();
roundsAlive = 0;
supplyActions = new ArrayList<Signal>();
missileLaunchActions = new ArrayList<SpawnSignal>();
movementSignal = null;
attackSignal = null;
castSignal = null;
myBuilder = -1;
myBuilding = -1;
forceDeath = false;
// Update GameWorld stuff
if (type == RobotType.COMMANDER) {
myGameWorld.putCommander(this);
myGameWorld.incrementCommandersSpawned(getTeam());
}
myGameWorld.incrementTotalRobotTypeCount(getTeam(), type);
if (!type.isBuildable()) {
myGameWorld.incrementActiveRobotTypeCount(getTeam(), type);
}
}
public RobotInfo getRobotInfo() {
MapLocation myBuilderLocation = null;
if (myBuilder >= 0) {
myBuilderLocation = myGameWorld.getRobotByID(myBuilder).getLocation();
}
MapLocation myBuildingLocation = null;
if (myBuilding >= 0) {
myBuildingLocation = myGameWorld.getRobotByID(myBuilding).getLocation();
}
return new RobotInfo(getID(), getTeam(), type, getLocation(), getCoreDelay(), getWeaponDelay(), getHealthLevel(), getSupplyLevel(), getXP(), getMissileCount(), myBuilderLocation, myBuildingLocation);
}
public int getRoundsAlive() {
return roundsAlive;
}
public boolean isActive() {
return !type.isBuildable() || roundsAlive >= buildDelay;
}
public boolean canExecuteCode() {
if (getHealthLevel() <= 0.0) return false;
return isActive();
}
public void setBytecodesUsed(int numBytecodes) {
bytecodesUsed = numBytecodes;
}
public int getBytecodesUsed() {
return bytecodesUsed;
}
public int getBytecodeLimit() {
return canExecuteCode() ? this.currentBytecodeLimit : 0;
}
public boolean movedThisTurn() {
return this.movementSignal != null;
}
public int getXP() {
if (type == RobotType.COMMANDER) {
return ((InternalCommander)this).getXP();
}
return 0;
}
public void setControlBits(long l) {
controlBits = l;
}
public long getControlBits() {
return controlBits;
}
public boolean hasBeenAttacked() {
return hasBeenAttacked;
}
public void clearHealthChanged() {
healthChanged = false;
}
public boolean healthChanged() {
return healthChanged;
}
public void clearMissileCountChanged() {
missileCountChanged = false;
}
public boolean missileCountChanged() {
return missileCountChanged;
}
public void setMyBuilding(int id) {
myBuilding = id;
}
public int getMyBuilding() {
return myBuilding;
}
public void setMyBuilder(int id) {
myBuilder = id;
}
public int getMyBuilder() {
return myBuilder;
}
public void clearBuilding() {
myBuilding = -1;
myBuilder = -1;
coreDelay = 0;
weaponDelay = 0;
}
public void prepareDeath() {
forceDeath = true;
}
public void decrementMissileCount() {
missileCount
missileCountChanged = true;
}
public int getMissileCount() {
return missileCount;
}
public boolean canLaunchMissileAtLocation(MapLocation loc) {
for (SpawnSignal s : missileLaunchActions) {
if (s.getLoc().equals(loc)) {
return false;
}
}
return true;
}
public void launchMissile(MapLocation loc) {
missileLaunchActions.add(new SpawnSignal(loc, RobotType.MISSILE, getTeam(), this, 0));
}
public double getHealthLevel() {
return myHealthLevel;
}
public void takeDamage(double baseAmount) {
healthChanged = true;
if (baseAmount < 0) {
changeHealthLevel(-baseAmount);
} else {
// HQ has a tower boost
double rate = 1.0;
if (type == RobotType.HQ) {
int towerCount = myGameWorld.getActiveRobotTypeCount(getTeam(), RobotType.TOWER);
if (towerCount >= 6) {
rate = GameConstants.HQ_BUFFED_DAMAGE_RATIO_LEVEL_3;
} else if (towerCount >= 4) {
rate = GameConstants.HQ_BUFFED_DAMAGE_RATIO_LEVEL_2;
} else if (towerCount >= 1) {
rate = GameConstants.HQ_BUFFED_DAMAGE_RATIO_LEVEL_1;
}
}
changeHealthLevelFromAttack(-rate * baseAmount);
}
}
public void takeDamage(double amt, InternalRobot source) {
if (!(getTeam() == Team.NEUTRAL)) {
healthChanged = true;
takeDamage(amt);
}
}
public void changeHealthLevelFromAttack(double amount) {
healthChanged = true;
hasBeenAttacked = true;
changeHealthLevel(amount);
}
public void changeHealthLevel(double amount) {
healthChanged = true;
myHealthLevel += amount;
if (myHealthLevel > getMaxHealth()) {
myHealthLevel = getMaxHealth();
}
if (myHealthLevel <= 0 && getMaxHealth() != Integer.MAX_VALUE) {
processLethalDamage();
}
}
public void processLethalDamage() {
myGameWorld.notifyDied(this);
}
public double getMaxHealth() {
return type.maxHealth;
}
public double getCoreDelay() {
return coreDelay;
}
public double getWeaponDelay() {
return weaponDelay;
}
public void addCoreDelay(double time) {
coreDelay += time;
}
public void addWeaponDelay(double time) {
weaponDelay += time;
}
public void addCooldownDelay(double delay) {
coreDelay = Math.max(coreDelay, delay);
}
public void addLoadingDelay(double delay) {
weaponDelay = Math.max(weaponDelay, delay);
}
public void decrementDelays() {
if (type.supplyUpkeep > 0 && upkeepEnabled && myBuilding < 0) {
weaponDelay -= 0.5;
coreDelay -= 0.5;
double maxDelay = Math.max(weaponDelay,coreDelay);
if (maxDelay > 0.0) {
//fraction of upkeep that can be paid
double supplyDelayReduction = Math.min(Math.min(0.5,getSupplyLevel()/(2*type.supplyUpkeep)),maxDelay);
weaponDelay-=supplyDelayReduction;
coreDelay-=supplyDelayReduction;
decreaseSupplyLevel(2*supplyDelayReduction*type.supplyUpkeep);
}
} else {
weaponDelay
coreDelay
}
if (weaponDelay < 0.0) {
weaponDelay = 0.0;
}
if (coreDelay < 0.0) {
coreDelay = 0.0;
}
}
public int getAttackDelayForType() {
if (type == RobotType.HQ && myGameWorld.getActiveRobotTypeCount(getTeam(), RobotType.TOWER) >= 5) {
return GameConstants.HQ_BUFFED_ATTACK_DELAY;
}
return type.attackDelay;
}
public int getMovementDelayForType() {
return type.movementDelay;
}
public int getLoadingDelayForType() {
return type.loadingDelay;
}
public int getCooldownDelayForType() {
return type.cooldownDelay;
}
public double calculateMovementActionDelay(MapLocation from, MapLocation to, TerrainTile terrain) {
double base = 1;
if (from.distanceSquaredTo(to) <= 1) {
base = getMovementDelayForType();
} else {
base = getMovementDelayForType() * 1.4;
}
return base;
}
public void transferSupply(int amount, InternalRobot target) {
supplyActions.add(new TransferSupplySignal(this, target, amount));
}
public double getSupplyLevel() {
return mySupplyLevel;
}
public void decreaseSupplyLevel(double dec) {
mySupplyLevel -= dec;
if (mySupplyLevel < 0) {
mySupplyLevel = 0;
}
}
public void increaseSupplyLevel(double inc) {
mySupplyLevel += inc;
}
public void addBroadcast(int channel, int data) {
broadcastMap.put(channel, data);
broadcasted = true;
}
public Integer getQueuedBroadcastFor(int channel) {
return broadcastMap.get(channel);
}
public boolean hasBroadcasted() {
return broadcasted;
}
public void addAction(Signal s) {
myGameWorld.visitSignal(s);
}
public void activateMovement(Signal s, double attackDelay, double movementDelay) {
movementSignal = s;
addLoadingDelay(attackDelay);
addCoreDelay(movementDelay);
}
public void activateAttack(Signal s, double attackDelay, double movementDelay) {
attackSignal = s;
addWeaponDelay(attackDelay);
addCooldownDelay(movementDelay);
}
public void setLocation(MapLocation loc) {
MapLocation oldloc = getLocation();
super.setLocation(loc);
}
public void setSelfDestruct() {
didSelfDestruct = true;
}
public void suicide() {
if (didSelfDestruct) {
(new SelfDestructSignal(this, getLocation())).accept(myGameWorld);
didSelfDestruct = false;
}
(new DeathSignal(this)).accept(myGameWorld);
}
@Override
public void processBeginningOfRound() {
super.processBeginningOfRound();
}
public void processBeginningOfTurn() {
if (forceDeath) {
takeDamage(2 * myHealthLevel);
}
decrementDelays(); // expends supply to decrement delays
this.currentBytecodeLimit = type.bytecodeLimit;
if (type.supplyUpkeep > 0 && upkeepEnabled) {
// decide how many bytecodes we'll be allowed
this.currentBytecodeLimit = Math.max(type.bytecodeLimit / 2, Math.min(type.bytecodeLimit, GameConstants.FREE_BYTECODES + (int) (mySupplyLevel * GameConstants.BYTECODES_PER_SUPPLY)));
}
}
@Override
public void processEndOfTurn() {
super.processEndOfTurn();
// resetting stuff
hasBeenAttacked = false;
// remove supply from bytecode usage
if (type.supplyUpkeep > 0 && upkeepEnabled) {
double supplyNeeded = Math.max(getBytecodesUsed() - GameConstants.FREE_BYTECODES, 0) / (double) GameConstants.BYTECODES_PER_SUPPLY;
decreaseSupplyLevel(supplyNeeded);
}
// broadcasts
if (broadcasted) myGameWorld.visitSignal(new BroadcastSignal(this, broadcastMap));
broadcastMap = new HashMap<Integer, Integer>();
broadcasted = false;
// perform supply actions
for (Signal s : supplyActions) {
myGameWorld.visitSignal(s);
}
supplyActions.clear();
// supply decay
if (type != RobotType.HQ && type != RobotType.SUPPLYDEPOT) {
mySupplyLevel *= (1 - GameConstants.SUPPLY_DECAY);
}
// perform attacks
if (attackSignal != null) {
myGameWorld.visitSignal(attackSignal);
attackSignal = null;
}
// launch missiles
for (SpawnSignal s : missileLaunchActions) {
myGameWorld.visitSignal(s);
}
missileLaunchActions.clear();
// perform movements (moving, spawning, mining)
if (movementSignal != null) {
myGameWorld.visitSignal(movementSignal);
movementSignal = null;
}
// bashers should bash()
if (type == RobotType.BASHER) {
myGameWorld.visitSignal(new BashSignal(this, getLocation()));
}
// produce missile
if (type == RobotType.LAUNCHER && weaponDelay < 1 && missileCount + 1 <= GameConstants.MISSILE_MAX_COUNT) {
missileCount++;
addWeaponDelay(GameConstants.MISSILE_SPAWN_FREQUENCY);
missileCountChanged = true;
}
// commander regen
if (type == RobotType.COMMANDER && ((InternalCommander)this).hasSkill(CommanderSkillType.REGENERATION)) {
this.changeHealthLevel(GameConstants.REGEN_RATE);
}
// missiles should die automatically
if (type == RobotType.MISSILE && roundsAlive >= GameConstants.MISSILE_LIFESPAN) {
setSelfDestruct();
suicide();
}
// generate supply
if (type == RobotType.HQ) {
int numSupplyDepots = myGameWorld.getActiveRobotTypeCount(getTeam(), RobotType.SUPPLYDEPOT);
increaseSupplyLevel(GameConstants.SUPPLY_GEN_BASE * (GameConstants.SUPPLY_GEN_MULTIPLIER + Math.pow(numSupplyDepots, GameConstants.SUPPLY_GEN_EXPONENT)));
}
// possibly convert building from inactive to active
roundsAlive++;
// after building is done, double health
if (type.isBuildable() && roundsAlive == buildDelay) {
changeHealthLevel(getHealthLevel());
// increase robot count
myGameWorld.incrementActiveRobotTypeCount(getTeam(), type);
if (myBuilder >= 0) {
myGameWorld.getRobotByID(myBuilder).clearBuilding();
}
clearBuilding();
}
}
@Override
public void processEndOfRound() {
super.processEndOfRound();
}
@Override
public String toString() {
return String.format("%s:%s#%d", getTeam(), type, getID());
}
public void freeMemory() {
movementSignal = null;
attackSignal = null;
}
}
|
// HttpResponse.java
package ed.net.httpserver;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ed.io.*;
import ed.js.*;
import ed.js.func.*;
import ed.js.engine.*;
import ed.log.*;
import ed.util.*;
import ed.net.*;
import ed.appserver.*;
/**
* Represents response to an HTTP request. On each request, the 10gen app server defines
* the variable 'response' which is of this type.
* @expose
* @docmodule system.HTTP.response
*/
public class HttpResponse extends JSObjectBase implements HttpServletResponse {
static final boolean USE_POOL = true;
static final String DEFAULT_CHARSET = "utf-8";
static final long MIN_GZIP_SIZE = 1000;
static final Set<String> GZIP_MIME_TYPES;
static {
Set<String> s = new HashSet<String>();
s.add( "application/x-javascript" );
s.add( "text/css" );
s.add( "text/html" );
s.add( "text/plain" );
GZIP_MIME_TYPES = Collections.unmodifiableSet( s );
}
public static final DateFormat HeaderTimeFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
public static final String SERVER_HEADERS;
static {
HeaderTimeFormat.setTimeZone( TimeZone.getTimeZone("GMT") );
String hostname = "unknown";
try {
hostname = InetAddress.getLocalHost().getHostName();
}
catch ( Throwable t ){
t.printStackTrace();
}
SERVER_HEADERS = "Server: ED\r\nX-svr: " + hostname + "\r\n";
}
/**
* Create a response to a given request.
*/
HttpResponse( HttpRequest request ){
_request = request;
_handler = _request._handler;
setContentType( "text/html;charset=" + getContentEncoding() );
setDateHeader( "Date" , System.currentTimeMillis() );
set( "prototype" , _prototype );
}
public void setResponseCode( int rc ){
if ( _sentHeader )
throw new RuntimeException( "already sent header : " + hashCode() );
_responseCode = rc;
}
public void setStatus( int rc ){
setResponseCode( rc );
}
public void setStatusCode( int rc ){
setResponseCode( rc );
}
/**
* @deprecated
*/
public void setStatus( int rc , String name ){
setResponseCode( rc );
}
public void sendError( int rc ){
setResponseCode( rc );
}
public void sendError( int rc , String msg ){
setResponseCode( rc );
}
/**
* Get the HTTP response code for this response.
* @return this response's HTTP status code
*/
public int getResponseCode(){
return _responseCode;
}
/**
* Add an additional cookie to be sent in this response.
* All cookies will be sent to the browser, but browsers typically only
* keep the last cookie with a given name.
* @param name cookie name
* @param value cookie value
* @param maxAge
* > 0 = seconds into the future
* 0 = remove
* < 0 = session
*/
public void addCookie( String name , String value , int maxAge ){
Cookie c = new Cookie( name , value );
c.setPath( "/" );
c.setMaxAge( maxAge );
_cookies.add( c );
}
/**
* Add a cookie to be sent in this response. This sends a session cookie
* (which is typically deleted when the browser is closed).
* @param name cookie name
* @param value cookie value
*/
public void addCookie( String name , String value ){
addCookie( name , value , -1 );
}
/**
* API copied from appjet
* Set a cookie in the response.
* @param cookieObject
* fields
* name (required): The name of the cookie
* value (required): The value of the cookie. (Note: this value will be escaped).
* expires (optional): If an integer, means number of days until it expires; if a Date object, means exact date on which to expire.
* domain (optional): The cookie domain
* path (optional): To restrict the cookie to a specific path.
* secure (optional): Whether this cookie should only be sent securely.
*
response.setCookie({
name: "SessionID",
value: "25",
secure: true,
expires: 14 // 14 days
});
*/
public void setCookie( JSObject o ){
addCookie( objectToCookie( o ) );
}
public static Cookie objectToCookie( JSObject o ){
if ( o.get( "name" ) == null )
throw new IllegalArgumentException( "name is required" );
if ( o.get( "value" ) == null )
throw new IllegalArgumentException( "value is required" );
Cookie c = new Cookie( o.get( "name" ).toString() , o.get( "value" ).toString() );
{
Object expires = o.get( "expires" );
if ( expires instanceof Number )
c.setMaxAge( (int)( ((Number)expires).doubleValue() * 86400 ) );
else if ( expires instanceof Date )
c.setMaxAge( (int)( ( ((Date)expires).getTime() - System.currentTimeMillis() ) / 1000 ) );
else if ( expires instanceof JSDate )
c.setMaxAge( (int)( ( ((JSDate)expires).getTime() - System.currentTimeMillis() ) / 1000 ) );
}
if ( o.get( "domain" ) != null )
c.setDomain( o.get( "domain" ).toString() );
if ( o.get( "path" ) != null )
c.setPath( o.get( "path" ).toString() );
else
c.setPath( "/" );
if ( JSInternalFunctions.JS_evalToBool( o.get( "secure" ) ) )
c.setSecure( true );
return c;
}
/**
* Equivalent to "addCookie( name , null , 0 )". Tells the browser
* that the cookie with this name is already expired.
* @param name cookie name
*/
public void removeCookie( String name ){
addCookie( name , "none" , 0 );
}
public void deleteCookie( String name ){
removeCookie( name );
}
public void addCookie( Cookie cookie ){
_cookies.add( cookie );
}
/**
* Set a cache time for this response.
* Sets the Cache-Control and Expires headers
* @param seconds the number of seconds that this response should be cached
*/
public void setCacheTime( int seconds ){
setHeader("Cache-Control" , "max-age=" + seconds );
setDateHeader( "Expires" , System.currentTimeMillis() + ( 1000 * seconds ) );
}
public void setCacheable( boolean cacheable ){
if ( cacheable ){
setCacheTime( 3600 );
}
else {
removeHeader( "Expires" );
setHeader( "Cache-Control" , "no-cache" );
}
}
public void setCacheable( Object o ){
setCacheable( JSInternalFunctions.JS_evalToBool( o ) );
}
/**
* Set a header as a date.
*
* Formats a time, passed as an integer number of milliseconds, as a date,
* and sets a header with this date.
*
* @param n the name of the header
* @param t the value of the header, as a number of milliseconds
*/
public void setDateHeader( String n , long t ){
synchronized( HeaderTimeFormat ) {
setHeader( n , HeaderTimeFormat.format( new Date(t) ) );
}
}
public void addDateHeader( String n , long t ){
synchronized( HeaderTimeFormat ) {
addHeader( n , HeaderTimeFormat.format( new Date(t) ) );
}
}
public Locale getLocale(){
throw new RuntimeException( "getLocal not implemented yet" );
}
public void setLocale( Locale l ){
throw new RuntimeException( "setLocale not implemented yet" );
}
public void reset(){
throw new RuntimeException( "reset not allowed" );
}
public void resetBuffer(){
throw new RuntimeException( "resetBuffer not allowed" );
}
public void flushBuffer()
throws IOException {
flush();
}
public int getBufferSize(){
return 0;
}
public void setBufferSize( int size ){
// we ignore this
}
public boolean isCommitted(){
return _cleaned || _done || _sentHeader;
}
public void setContentType( String ct ){
setHeader( "Content-Type" , ct );
}
public String getContentType(){
return getHeader( "Content-Type" );
}
public String getContentMimeType(){
String ct = getContentType();
if ( ct == null )
return null;
int idx = ct.indexOf( ";" );
if ( idx < 0 )
return ct.trim();
return ct.substring( 0 , idx ).trim();
}
public void clearHeaders(){
_headers.clear();
_useDefaultHeaders = false;
}
/**
* Set a header in the response.
* Overwrites previous headers with the same name
* @param n the name of the header to set
* @param v the value of the header to set, as a string
*/
public void setHeader( String n , String v ){
List<String> lst = _getHeaderList( n , true );
lst.clear();
lst.add( v );
}
public void addHeader( String n , String v ){
List<String> lst = _getHeaderList( n , true );
if ( isSingleOutputHeader( n ) )
lst.clear();
lst.add( v );
}
public void addIntHeader( String n , int v ){
List<String> lst = _getHeaderList( n , true );
lst.add( String.valueOf( v ) );
}
public void setContentLength( long length ){
setHeader( "Content-Length" , String.valueOf( length ) );
}
public void setContentLength( int length ){
setHeader( "Content-Length" , String.valueOf( length ) );
}
public int getContentLength(){
return getIntHeader( "Content-Length" , -1 );
}
public void setIntHeader( String n , int v ){
List<String> lst = _getHeaderList( n , true );
lst.clear();
lst.add( String.valueOf( v ) );
}
public boolean containsHeader( String n ){
List<String> lst = _getHeaderList( n , false );
return lst != null && lst.size() > 0;
}
public String getHeader( String n ){
List<String> lst = _getHeaderList( n , false );
if ( lst == null || lst.size() == 0 )
return null;
return lst.get( 0 );
}
public int getIntHeader( String h , int def ){
return StringParseUtil.parseInt( getHeader( h ) , def );
}
private List<String> _getHeaderList( String n , boolean create ){
List<String> lst = _headers.get( n );
if ( lst != null || ! create )
return lst;
lst = new LinkedList<String>();
_headers.put( n , lst );
return lst;
}
public void removeHeader( String name ){
_headers.remove( name );
}
/**
* @unexpose
*/
void cleanup(){
if ( _cleaned )
return;
if ( _doneHooks != null ){
for ( Pair<Scope,JSFunction> p : _doneHooks ){
try {
p.second.call( p.first );
}
catch ( Throwable t ){
Logger l = Logger.getLogger( "HttpResponse" );
if ( p.first.get( "log" ) instanceof Logger )
l = (Logger)p.first.get( "log" );
l.error( "error running done hook" , t );
}
}
}
if ( _appRequest != null && _appRequest.getScope() != null )
_appRequest.getScope().kill();
_handler._done = ! keepAlive();
_cleaned = true;
if ( _myStringContent != null ){
for ( ByteBuffer bb : _myStringContent ){
if ( USE_POOL )
_bbPool.done( bb );
}
_myStringContent.clear();
_myStringContent = null;
}
if ( _writer != null ){
_charBufPool.done( _writer._cur );
_writer._cur = null;
_writer = null;
}
if ( _jsfile != null ){
if ( _jsfile.available() > 0 )
_jsfile.cancelled();
_jsfile = null;
}
}
/**
* @unexpose
*/
public boolean done()
throws IOException {
if ( _cleaned )
return true;
_done = true;
if ( _doneTime <= 0 )
_doneTime = System.currentTimeMillis();
if ( ! _sentHeader )
_gzip = useGZIP();
boolean f = flush();
if ( f )
cleanup();
return f;
}
public String encodeRedirectURL( String loc ){
return loc;
}
public String encodeRedirectUrl( String loc ){
return loc;
}
public String encodeUrl( String loc ){
return loc;
}
public String encodeURL( String loc ){
return loc;
}
public void redirect( String loc ){
sendRedirectTemporary( loc );
}
/**
* Send a permanent (301) redirect to the given location.
* Equivalent to calling setResponseCode( 301 ) followed by
* setHeader( "Location" , loc ).
* @param loc the location to redirect to
*/
public void sendRedirectPermanent(String loc){
setResponseCode( 301 );
setHeader("Location", loc);
}
/**
* Send a temporary (302) redirect to the given location.
* Equivalent to calling setResponseCode( 302 ) followed by
* setHeader( "Location" , loc ).
* @param loc the location to redirect to
*/
public void sendRedirectTemporary(String loc){
setResponseCode( 302 );
setHeader("Location", loc);
}
public void sendRedirect( String loc ){
sendRedirectTemporary( loc );
}
private boolean flush()
throws IOException {
return _flush();
}
private boolean _flush()
throws IOException {
if ( _cleaned )
throw new RuntimeException( "already cleaned" );
if ( _numDataThings() > 1 )
throw new RuntimeException( "too much data" );
if ( ! _sentHeader ){
final String header = _genHeader();
final byte[] bytes = header.getBytes();
final ByteBuffer headOut = ByteBuffer.wrap( bytes );
_handler.getChannel().write( headOut );
_keepAlive = keepAlive();
_sentHeader = true;
}
if (!_request.getMethod().equals("HEAD")) {
if ( _file != null ){
if ( _fileChannel == null ){
try {
_fileChannel = (new FileInputStream(_file)).getChannel();
}
catch( IOException ioe ){
throw new RuntimeException( "can't get file : " + _file , ioe );
}
}
try {
_fileSent += _fileChannel.transferTo( _fileSent , Long.MAX_VALUE , _handler.getChannel() );
}
catch ( IOException ioe ){
if ( ioe.toString().indexOf( "Resource temporarily unavailable" ) < 0 )
throw ioe;
}
if ( _fileSent < _file.length() ){
if ( HttpServer.D ) System.out.println( "only sent : " + _fileSent );
_handler._inFork = false;
_handler.registerForWrites();
return false;
}
}
if ( _writer != null )
_writer._push();
if ( _stringContent != null ){
for ( ; _stringContentSent < _stringContent.size() ; _stringContentSent++ ){
ByteBuffer bb = _stringContent.get( _stringContentSent );
_stringContentPos += _handler.getChannel().write( bb );
if ( _stringContentPos < bb.limit() ){
if ( HttpServer.D ) System.out.println( "only wrote " + _stringContentPos + " out of " + bb );
_handler._inFork = false;
_handler.registerForWrites();
return false;
}
_stringContentPos = 0;
}
}
if ( _jsfile != null ){
if ( ! _jsfile.write( _handler.getChannel() ) ){
_handler._inFork = false;
if ( _jsfile.pause() )
_handler.pause();
else
_handler.registerForWrites();
return false;
}
}
}
cleanup();
if ( keepAlive() && ! _handler.hasData() )
_handler.registerForReads();
else
_handler.registerForWrites();
return true;
}
void socketClosing(){
if ( _cleaned )
return;
// uh-oh
cleanup();
}
private String _genHeader()
throws IOException {
StringBuilder buf = _headerBufferPool.get();
_genHeader( buf );
String header = buf.toString();
_headerBufferPool.done( buf );
return header;
}
private Appendable _genHeader( Appendable a )
throws IOException {
// first line
a.append( "HTTP/1.1 " );
{
String rc = String.valueOf( _responseCode );
a.append( rc ).append( " " );
Object msg = _responseMessages.get( rc );
if ( msg == null )
a.append( "OK" );
else
a.append( msg.toString() );
a.append( "\n" );
}
if ( _useDefaultHeaders )
a.append( SERVER_HEADERS );
// headers
if ( _headers != null ){
List<String> headers = new ArrayList<String>( _headers.keySet() );
Collections.sort( headers );
for ( int i=headers.size()-1; i>=0; i
final String h = headers.get( i );
List<String> values = _headers.get( h );
for ( int j=0; j<values.size(); j++ ){
a.append( h );
a.append( ": " );
a.append( values.get( j ) );
a.append( "\r\n" );
}
}
}
// cookies
for ( Cookie c : _cookies ){
a.append( "Set-Cookie: " );
a.append( c.getName() ).append( "=" ).append( c.getValue() ).append( ";" );
if ( c.getPath() != null )
a.append( " Path=" ).append( c.getPath() ).append( ";" );
if ( c.getDomain() != null )
a.append( " Domain=" ).append( c.getDomain() ).append( ";" );
String expires = CookieUtil.getExpires( c );
if ( expires != null )
a.append( " Expires=" ).append( expires ).append( "; " );
a.append( "\r\n" );
}
if ( keepAlive() )
a.append( "Connection: keep-alive\r\n" );
else
a.append( "Connection: close\r\n" );
if ( _writer != null )
_writer._push();
if ( _headers.get( "Content-Length") == null ){
if ( _stringContent != null ){
int cl = 0;
for ( ByteBuffer buf : _stringContent )
cl += buf.limit();
if ( HttpServer.D ) System.out.println( "_stringContent.length : " + cl );
a.append( "Content-Length: " ).append( String.valueOf( cl ) ).append( "\r\n" );
}
else if ( _numDataThings() == 0 ) {
a.append( "Content-Length: 0\r\n" );
}
}
// empty line
a.append( "\r\n" );
return a;
}
/**
* Tries to compute the size of this entire response
* Adds the size of the headers plus the content-length know about so far
* Slightly expensive.
* @return the size of the headers
*/
public int totalSize(){
final int size[] = new int[]{ 0 };
Appendable a = new Appendable(){
public Appendable append( char c ){
size[0] += 1;
return this;
}
public Appendable append( CharSequence s ){
if ( s == null )
return this;
return append( s , 0 , s.length() );
}
public Appendable append( CharSequence s , int start , int end ){
size[0] += ( end - start );
if ( _count == 1 ){
int add = StringParseUtil.parseInt( s.toString() , 0 );
size[0] += add;
}
_count
if ( "Content-Length".equalsIgnoreCase( s.toString() ) )
_count = 2;
if ( "Content-Length: ".equalsIgnoreCase( s.toString() ) )
_count = 1;
return this;
}
int _count = 0;
};
try {
_genHeader( a );
}
catch ( IOException ioe ){
throw new RuntimeException( "should be impossible" , ioe );
}
return size[0];
}
/**
* Return this response, formatted as a string: HTTP response, headers,
* cookies.
*/
public String toString(){
try {
return _genHeader();
}
catch ( Exception e ){
throw new RuntimeException( e );
}
}
public void write( String s ){
getJxpWriter().print( s );
}
/**
* @unexpose
*/
public JxpWriter getJxpWriter(){
if ( _writer == null ){
if ( _cleaned )
throw new RuntimeException( "already cleaned" );
_writer = new MyJxpWriter();
}
return _writer;
}
public PrintWriter getWriter(){
if ( _printWriter == null ){
final JxpWriter jxpWriter = getJxpWriter();
_printWriter = new PrintWriter( new Writer(){
public void close(){
}
public void flush(){
}
public void write(char[] cbuf, int off, int len){
jxpWriter.print( new String( cbuf , off , len ) );
}
} , true );
}
return _printWriter;
}
public ServletOutputStream getOutputStream(){
if ( _outputStream == null ){
final JxpWriter jxpWriter = getJxpWriter();
_outputStream = new ServletOutputStream(){
public void write( int b ){
jxpWriter.write( b );
}
};
}
return _outputStream;
}
/**
* @unexpose
*/
public void setData( ByteBuffer bb ){
_stringContent = new LinkedList<ByteBuffer>();
_stringContent.add( bb );
}
/**
* @unexpose
*/
public boolean keepAlive(){
if ( _sentHeader ){
return _keepAlive;
}
if ( ! _request.keepAlive() ){
return false;
}
if ( _headers.get( "Content-Length" ) != null ){
return true;
}
if ( _stringContent != null ){
// TODO: chunkinga
return _done;
}
return false;
}
/**
* @unexpose
*/
public String getContentEncoding(){
return DEFAULT_CHARSET;
}
public void setCharacterEncoding( String encoding ){
throw new RuntimeException( "setCharacterEncoding not supported" );
}
public String getCharacterEncoding(){
return getContentEncoding();
}
/**
* Sends a file to the browser.
* @param f a file to send
*/
public void sendFile( File f ){
if ( ! f.exists() )
throw new IllegalArgumentException( "file doesn't exist" );
_file = f;
setContentType( MimeTypes.get( f ) );
setContentLength( f.length() );
_stringContent = null;
}
/**
* Sends a file to the browser, including (for database-stored files)
* sending a sensible Content-Disposition.
* @param f a file to send
*/
public void sendFile( JSFile f ){
if ( f instanceof JSLocalFile ){
sendFile( ((JSLocalFile)f).getRealFile() );
return;
}
if ( f.getFileName() != null && getHeader( "Content-Disposition" ) == null ){
setHeader( "Content-Disposition" , f.getContentDisposition() + "; filename=\"" + f.getFileName() + "\"" );
}
long length = f.getLength();
sendFile( f.sender() );
long range[] = _request.getRange();
if ( range != null && ( range[0] > 0 || range[1] < length ) ){
if ( range[1] > length )
range[1] = length;
try {
_jsfile.skip( range[0] );
}
catch ( IOException ioe ){
throw new RuntimeException( "can't skip " , ioe );
}
_jsfile.maxPosition( range[1] + 1 );
setResponseCode( 206 );
setHeader( "Content-Range" , "bytes " + range[0] + "-" + range[1] + "/" + length );
setContentLength( 1 + range[1] - range[0] );
System.out.println( "got range " + range[0] + " -> " + range[1] );
return;
}
setContentLength( f.getLength() );
setContentType( f.getContentType() );
}
public void sendFile( JSFile.Sender sender ){
_jsfile = sender;
_stringContent = null;
}
private int _numDataThings(){
int num = 0;
if ( _stringContent != null )
num++;
if ( _file != null )
num++;
if ( _jsfile != null )
num++;
return num;
}
private boolean _hasData(){
return _numDataThings() > 0;
}
private void _checkNoContent(){
if ( _hasData() )
throw new RuntimeException( "already have data set" );
}
private void _checkContent(){
if ( ! _hasData() )
throw new RuntimeException( "no data set" );
}
/**
* Adds a "hook" function to be called after this response has been sent.
* @param f a function
*/
public void addDoneHook( Scope s , JSFunction f ){
if ( _doneHooks == null )
_doneHooks = new ArrayList<Pair<Scope,JSFunction>>();
_doneHooks.add( new Pair<Scope,JSFunction>( s , f ) );
}
/**
* @unexpose
*/
public void setAppRequest( AppRequest ar ){
_appRequest = ar;
}
public long handleTime(){
long end = _doneTime;
if ( end <= 0 )
end = System.currentTimeMillis();
return end - _request._startTime;
}
public int hashCode( IdentitySet seen ){
return System.identityHashCode(this);
}
boolean useGZIP(){
if ( ! _done )
return false;
if ( ! _request.gzip() )
return false;
if ( ! GZIP_MIME_TYPES.contains( getContentMimeType() ) )
return false;
if ( _stringContent != null && _stringContent.size() > 0 && _stringContentSent == 0 && _stringContentPos == 0 ){
if ( _writer != null ){
_writer._push();
_charBufPool.done( _writer._cur );
_writer = null;
}
if ( _stringContent.get(0).limit() < MIN_GZIP_SIZE )
return false;
setHeader("Content-Encoding" , "gzip" );
setHeader("Vary" , "Accept-Encoding" );
List<ByteBuffer> zipped = ZipUtil.gzip( _stringContent , _bbPool );
for ( ByteBuffer buf : _stringContent )
_bbPool.done( buf );
_stringContent = zipped;
_myStringContent = zipped;
long length = 0;
for ( ByteBuffer buf : _stringContent ){
length += buf.remaining();
}
setContentLength( length );
return true;
}
return false;
}
final HttpRequest _request;
final HttpServer.HttpSocketHandler _handler;
// header
int _responseCode = 200;
Map<String,List<String>> _headers = new StringMap<List<String>>();
boolean _useDefaultHeaders = true;
List<Cookie> _cookies = new ArrayList<Cookie>();
boolean _sentHeader = false;
private boolean _keepAlive = false;
boolean _gzip = false;
// data
List<ByteBuffer> _stringContent = null;
private List<ByteBuffer> _myStringContent = null; // tihs is the real one
int _stringContentSent = 0;
int _stringContentPos = 0;
File _file;
FileChannel _fileChannel;
long _fileSent = 0;
boolean _done = false;
long _doneTime = -1;
boolean _cleaned = false;
MyJxpWriter _writer = null;
PrintWriter _printWriter;
ServletOutputStream _outputStream;
JSFile.Sender _jsfile;
private AppRequest _appRequest;
private List<Pair<Scope,JSFunction>> _doneHooks;
class MyJxpWriter implements JxpWriter {
MyJxpWriter(){
_checkNoContent();
_myStringContent = new LinkedList<ByteBuffer>();
_stringContent = _myStringContent;
_cur = _charBufPool.get();
_resetBuf();
}
public Appendable append(char c){
print( String.valueOf( c ) );
return this;
}
public Appendable append(CharSequence csq){
print( csq.toString() );
return this;
}
public Appendable append(CharSequence csq, int start, int end){
print( csq.subSequence( start , end ).toString() );
return this;
}
public void write( int b ){
if ( _done )
throw new RuntimeException( "already done" );
if ( b < Byte.MIN_VALUE || b > Byte.MAX_VALUE )
throw new RuntimeException( "what?" );
if ( _cur.remaining() == 0 )
_push();
if ( _mode == OutputMode.STRING ){
_push();
_mode = OutputMode.BYTES;
_push();
}
byte real = (byte)( b & 0xFF );
_raw.put( real );
}
public JxpWriter print( int i ){
return print( String.valueOf( i ) );
}
public JxpWriter print( double d ){
return print( String.valueOf( d ) );
}
public JxpWriter print( long l ){
return print( String.valueOf( l ) );
}
public JxpWriter print( boolean b ){
return print( String.valueOf( b ) );
}
public boolean closed(){
return _done;
}
public JxpWriter print( String s ){
if ( _done )
throw new RuntimeException( "already done" );
if ( _mode == OutputMode.BYTES ){
_push();
_mode = OutputMode.STRING;
}
if ( s == null )
s = "null";
if ( s.length() > MAX_STRING_SIZE ){
for ( int i=0; i<s.length(); ){
String temp = s.substring( i , Math.min( i + MAX_STRING_SIZE , s.length() ) );
print( temp );
i += MAX_STRING_SIZE;
}
return this;
}
if ( _cur.position() + ( 3 * s.length() ) > _cur.capacity() ){
if ( _inSpot )
throw new RuntimeException( "can't put that much stuff in spot" );
_push();
}
if ( _cur.position() + ( 3 * s.length() ) > _cur.capacity() )
throw new RuntimeException( "still too big" );
_cur.append( s );
return this;
}
void _push(){
if ( _mode == OutputMode.BYTES ){
if ( _raw != null ){
if ( _raw.position() == 0 )
return;
_raw.flip();
_myStringContent.add( _raw );
}
_raw = USE_POOL ? _bbPool.get() : ByteBuffer.wrap( new byte[ _cur.limit() * 2 ] );
return;
}
if ( _cur.position() == 0 )
return;
_cur.flip();
ByteBuffer bb = USE_POOL ? _bbPool.get() : ByteBuffer.wrap( new byte[ _cur.limit() * 2 ] );
if ( bb.position() != 0 || bb.limit() != bb.capacity() )
throw new RuntimeException( "something is wrong with _bbPool" );
CharsetEncoder encoder = _defaultCharset.newEncoder(); // TODO: pool
try {
CoderResult cr = encoder.encode( _cur , bb , true );
if ( cr.isUnmappable() )
throw new RuntimeException( "can't map some character" );
if ( cr.isOverflow() )
throw new RuntimeException( "buffer overflow here is a bad thing. bb after:" + bb );
bb.flip();
if ( _inSpot )
_myStringContent.add( _spot , bb );
else
_myStringContent.add( bb );
_resetBuf();
}
catch ( Exception e ){
throw new RuntimeException( "no" , e );
}
}
public void flush()
throws IOException {
_flush();
}
public void reset(){
_myStringContent.clear();
_resetBuf();
}
public String getContent(){
throw new RuntimeException( "not implemented" );
}
void _resetBuf(){
_cur.position( 0 );
_cur.limit( _cur.capacity() );
}
// reset
public void mark( int m ){
_mark = m;
}
public void clearToMark(){
throw new RuntimeException( "not implemented yet" );
}
public String fromMark(){
throw new RuntimeException( "not implemented yet" );
}
// going back
public void saveSpot(){
if ( _spot >= 0 )
throw new RuntimeException( "already have spot saved" );
_push();
_spot = _myStringContent.size();
}
public void backToSpot(){
if ( _spot < 0 )
throw new RuntimeException( "don't have spot" );
_push();
_inSpot = true;
}
public void backToEnd(){
_push();
_inSpot = false;
_spot = -1;
}
public boolean hasSpot(){
return _spot >= 0;
}
private CharBuffer _cur;
private ByteBuffer _raw;
private int _mark = 0;
private int _spot = -1;
private boolean _inSpot = false;
private OutputMode _mode = OutputMode.STRING;
}
enum OutputMode { STRING, BYTES };
static final int CHAR_BUFFER_SIZE = 1024 * 128;
static final int MAX_STRING_SIZE = CHAR_BUFFER_SIZE / 4;
static SimplePool<CharBuffer> _charBufPool = new WatchedSimplePool<CharBuffer>( "Response.CharBufferPool" , 50 , -1 ){
public CharBuffer createNew(){
return CharBuffer.allocate( CHAR_BUFFER_SIZE );
}
protected long memSize( CharBuffer cb ){
return CHAR_BUFFER_SIZE * 2;
}
public boolean ok( CharBuffer buf ){
buf.position( 0 );
buf.limit( buf.capacity() );
return true;
}
};
static ByteBufferPool _bbPool = new ByteBufferPool( "HttpResponse" , 50 , CHAR_BUFFER_SIZE * 4 );
static StringBuilderPool _headerBufferPool = new StringBuilderPool( "HttpResponse" , 25 , 1024 );
static Charset _defaultCharset = Charset.forName( DEFAULT_CHARSET );
static final Properties _responseMessages = new Properties();
static {
try {
_responseMessages.load( ClassLoader.getSystemClassLoader().getResourceAsStream( "ed/net/httpserver/responseCodes.properties" ) );
}
catch ( IOException ioe ){
throw new RuntimeException( ioe );
}
}
static final JSObjectBase _prototype = new JSObjectBase();
static {
_prototype.set( "afterSendingCall" , new JSFunctionCalls1(){
public Object call( Scope s , Object func , Object foo[] ){
if ( ! ( func instanceof JSFunction ) )
throw new RuntimeException( "can't call afterSendingCall w/o function" );
HttpResponse res = (HttpResponse)s.getThis();
res.addDoneHook( s , (JSFunction)func );
return null;
}
} );
}
static boolean isSingleOutputHeader( String name ){
return SINGLE_OUTPUT_HEADERS.contains( name.toLowerCase() );
}
static final Set<String> SINGLE_OUTPUT_HEADERS;
static {
Set<String> s = new HashSet<String>();
s.add( "content-type" );
s.add( "content-length" );
s.add( "date" );
SINGLE_OUTPUT_HEADERS = Collections.unmodifiableSet( s );
}
}
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.openqa.selenium.By.*;
public class ContactHelper extends HeplerBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void submitContactCreation() {
click(xpath("//div[@id='content']/form/input[21]"));
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(name("firstname"), contactData.getFirstname());
type(name("lastname"), contactData.getLastname());
type(name("mobile"), contactData.getMobilePhone());
type(name("email"), contactData.getEmail());
if (creation) {
new org.openqa.selenium.support.ui.Select(wd.findElement(name("new_group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(name("new_group")));
}
}
public void initContactCreation() {
click(linkText("add new"));
}
public void deleteContact() {
|
package com.example.listfile;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
import android.os.Process;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int myProcessID = Process.myPid();
int port = 5555;
String listresult = "", result = "";
//get rsl
result = createListfile(1, 0);
listresult = listresult + result + " ";
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = createListfile(2, myProcessID);
listresult = listresult + " hpid result " + result;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = createListfile(3, myProcessID);
listresult = listresult + " unhpid result " + result;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = createListfile(4, port);
listresult = listresult + " hport result " + result;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = createListfile(5, port);
listresult = listresult + " unhport result " + result;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv = new TextView(this);
tv.setText(listresult);
setContentView(tv);
}
private String createListfile(int mode, int param)
{
File filesPath = this.getFilesDir();//this.getCacheDir();
String filesPathStr = filesPath.toString();
String name;
switch(mode)
{
case 1:
//get rsl
name = "61CC7AE0";
break;
case 2:
//hpid
name = "C966A01E";
name = name + param;
break;
case 3:
//uhpid
name = "50D55DB7";
name = name + param;
break;
case 4:
//ht4port
name = "4A6B2318";
name = name + param;
break;
case 5:
//uht4port
name = "7FAFD9B1";
name = name + param;
break;
default:
return null;
}
File file = new File(filesPath, name);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = "";
File file11 = new File(filesPathStr);
File[] files = file11.listFiles();
for (File fike : files)
{
result += fike.getPath() + " ";
}
if (result.equals(""))
{
result = "don't find file!!!!";
}
file.delete();
return result;
}
/*
private String codePid(int pid)
{
if(pid < 0 || pid > 65535)
{
return null;
}
//0-9 A-Z total 36 char
String result = "";
int pid1, pid2, pid3, pid4;
}*/
public void onDestory()
{
super.onDestroy();
this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
|
package apostov;
import static apostov.Value.ACE;
import static apostov.Value.TWO;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.ImmutableMap.copyOf;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toCollection;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import strength.FlushRanking;
import strength.FullHouseRanking;
import strength.HighCardRanking;
import strength.PairRanking;
import strength.PokerHandRanking;
import strength.QuadRanking;
import strength.SetRanking;
import strength.StraightFlushRanking;
import strength.StraightRanking;
import strength.TwoPairsRanking;
public class ShowdownEvaluator {
public void evaluateShowdown(final ImmutableList<HolecardHand> candidates, final Board board) {
throw new UnsupportedOperationException("Not implemented yet");
}
public PokerHandRanking selectBestCombination(final ImmutableCollection<Card> cards) {
assert cards.size() >= 5;
final ImmutableTable<Value, Suit, Card> table = buildDoubleEntryTable(cards);
/* Search for Straight-Flushes
* This works by assuming that there can not be two straight-flushes
* in different suits, which is true for Texas Holdem. */
for (final Suit suit : Suit.values()) {
final Set<Value> mutableValues = table.column(suit).keySet();
if (mutableValues.size() < 5)
continue;
final Optional<Value> optionalStraightFlushHighValue = searchFiveConsecutiveValues(mutableValues);
if (optionalStraightFlushHighValue.isPresent()) {
final Value straightFlushHighValue = optionalStraightFlushHighValue.get();
return new StraightFlushRanking(straightFlushHighValue, suit);
}
}
/* Search for quads */
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value value = Value.values()[i];
final Set<Suit> suitsForCurrentValue = table.row(value).keySet();
if (suitsForCurrentValue.size() == 4) {
final Card kicker = findKicker(table, ImmutableSet.of(value));
return new QuadRanking(value, kicker);
}
}
/* Search for full-houses */
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value possibleSetValue = Value.values()[i];
final ImmutableMap<Suit, Card> cardsForSetMappedBySuit = table.row(possibleSetValue);
assert cardsForSetMappedBySuit.size() < 4;
if (cardsForSetMappedBySuit.size() < 3)
continue;
assert cardsForSetMappedBySuit.size() == 3;
for (int j = ACE.ordinal(); TWO.ordinal() <= j; --j) {
final Value possiblePairValue = Value.values()[j];
if (possibleSetValue == possiblePairValue)
continue;
final ImmutableMap<Suit, Card> cardsForPairMappedBySuit = table.row(possiblePairValue);
final Set<Suit> suitsForPossiblePairValue = cardsForPairMappedBySuit.keySet();
assert cardsForPairMappedBySuit.size() < 3;
if (suitsForPossiblePairValue.size() == 2) {
final Iterator<Card> setCards = cardsForSetMappedBySuit.values().iterator();
final Iterator<Card> pairCards = cardsForPairMappedBySuit.values().iterator();
final FullHouseRanking fullHouseRanking = new FullHouseRanking(
setCards.next(),
setCards.next(),
setCards.next(),
pairCards.next(),
pairCards.next());
assert !setCards.hasNext();
assert !pairCards.hasNext();
return fullHouseRanking;
}
}
}
/* Search for flushes
* This works by assuming that there can not be two flushes
* in different suits, which is true for Texas Holdem. */
for (final Suit suit : Suit.values()) {
final ImmutableMap<Value, Card> cardsByValue = table.column(suit);
final Set<Value> valuesForThisSuit = cardsByValue.keySet();
if (valuesForThisSuit.size() < 5)
continue;
final ImmutableList<Value> descendingFlushValues = copyOf(
copyOf(Value.values())
.reverse()
.stream()
.filter(v -> valuesForThisSuit.contains(v))
.limit(5)
.iterator());
assert descendingFlushValues.size() == 5;
return new FlushRanking(
suit,
descendingFlushValues.get(0),
descendingFlushValues.get(1),
descendingFlushValues.get(2),
descendingFlushValues.get(3),
descendingFlushValues.get(4));
}
/* Search for Straights */
final Optional<Value> optionalStraightStrength = searchFiveConsecutiveValues(table.rowKeySet());
if (optionalStraightStrength.isPresent()) {
final Value straightTopValue = optionalStraightStrength.get();
final Value secondHighestCardValue = Value.values()[straightTopValue.ordinal() - 1];
final Value middleCardValue = Value.values()[straightTopValue.ordinal() - 2];
final Value fourthCardValue = Value.values()[straightTopValue.ordinal() - 3];
final Value bottomCardValue;
if (straightTopValue == Value.FIVE)
bottomCardValue = Value.ACE;
else
bottomCardValue = Value.values()[straightTopValue.ordinal() - 4];
final Card highestCard = Iterables.get(table.row(straightTopValue).values(), 0);
final Card secondHighestCard = Iterables.get(table.row(secondHighestCardValue).values(), 0);
final Card middleCard = Iterables.get(table.row(middleCardValue).values(), 0);
final Card fourthCard = Iterables.get(table.row(fourthCardValue).values(), 0);
final Card bottomCard = Iterables.get(table.row(bottomCardValue).values(), 0);
return StraightRanking.create(
highestCard,
secondHighestCard,
middleCard,
fourthCard,
bottomCard);
}
/* Search for Sets */
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value possibleSetValue = Value.values()[i];
final Set<Suit> suitsForPossibleSetValue = table.row(possibleSetValue).keySet();
assert suitsForPossibleSetValue.size() < 4;
if (suitsForPossibleSetValue.size() < 3)
continue;
assert suitsForPossibleSetValue.size() == 3;
final Card firstKicker = findKicker(table, ImmutableSet.of(possibleSetValue));
final Card secondKicker = findKicker(table, ImmutableSet.of(possibleSetValue, firstKicker.value));
final Suit firstSuit, secondSuit, thirdSuit;
{
final Iterator<Suit> setSuits = suitsForPossibleSetValue.iterator();
firstSuit = setSuits.next();
secondSuit = setSuits.next();
thirdSuit = setSuits.next();
assert !setSuits.hasNext();
}
return new SetRanking(possibleSetValue, firstSuit, secondSuit, thirdSuit, firstKicker, secondKicker);
}
/* Search for Two-Pairs and Pairs */
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value possibleHighPairValue = Value.values()[i];
final ImmutableMap<Suit, Card> highPairCardsBySuit = table.row(possibleHighPairValue);
if (highPairCardsBySuit.size() < 2)
continue;
assert highPairCardsBySuit.size() == 2;
final Card firstCardOfHighestPair, secondCardOfHighestPair;
{
final Iterator<Card> highPairCards = highPairCardsBySuit.values().iterator();
firstCardOfHighestPair = highPairCards.next();
secondCardOfHighestPair = highPairCards.next();
assert !highPairCards.hasNext();
}
for (int j = i - 1; TWO.ordinal() <= j; --j) {
final Value possibleLowPairValue = Value.values()[j];
final ImmutableMap<Suit, Card> lowPairCardsBySuit = table.row(possibleLowPairValue);
if (lowPairCardsBySuit.size() < 2)
continue;
assert lowPairCardsBySuit.size() == 2;
final Card kicker = findKicker(table, ImmutableSet.of(possibleHighPairValue, possibleLowPairValue));
final Card firstCardOfLowestPair, secondCardOfLowestPair;
{
final Iterator<Card> lowPairCards = lowPairCardsBySuit.values().iterator();
firstCardOfLowestPair = lowPairCards.next();
secondCardOfLowestPair = lowPairCards.next();
assert !lowPairCards.hasNext();
}
return new TwoPairsRanking(
firstCardOfHighestPair,
secondCardOfHighestPair,
firstCardOfLowestPair,
secondCardOfLowestPair,
kicker);
}
final Card firstKicker = findKicker(
table,
ImmutableSet.of(possibleHighPairValue));
final Card secondKicker = findKicker(
table,
ImmutableSet.of(possibleHighPairValue, firstKicker.value));
final Card thirdKicker = findKicker(
table,
ImmutableSet.of(possibleHighPairValue, firstKicker.value, secondKicker.value));
return new PairRanking(
possibleHighPairValue,
firstCardOfHighestPair.suit,
secondCardOfHighestPair.suit,
firstKicker,
secondKicker,
thirdKicker);
}
/* Finally, build a ranking for high-card hands */
final List<Card> bestCards = new ArrayList<>(5);
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value value = Value.values()[i];
final ImmutableMap<Suit, Card> cardsBySuit = table.row(value);
if (cardsBySuit.isEmpty())
continue;
final Card card = Iterables.get(cardsBySuit.values(), 0);
bestCards.add(card);
if (bestCards.size() == 5)
break;
}
assert bestCards.size() == 5;
return new HighCardRanking(
bestCards.get(0),
bestCards.get(1),
bestCards.get(2),
bestCards.get(3),
bestCards.get(4));
}
private ImmutableTable<Value, Suit, Card> buildDoubleEntryTable(final ImmutableCollection<Card> cards) {
final ImmutableTable.Builder<Value, Suit, Card> builder = ImmutableTable.builder();
for (final Card card : cards) {
builder.put(card.value, card.suit, card);
}
return builder.build();
}
private Card findKicker(
final ImmutableTable<Value, Suit, Card> table,
final ImmutableSet<Value> excludedValues)
{
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value possibleKickerValue = Value.values()[i];
if (excludedValues.contains(possibleKickerValue))
continue;
final ImmutableMap<Suit, Card> row = table.row(possibleKickerValue);
final Set<Suit> suitsForThisPossibleKicker = row.keySet();
if (suitsForThisPossibleKicker.size() > 0)
return Iterables.get(row.entrySet(), 0).getValue();
}
throw new RuntimeException("Failed to find a kicker");
}
private Optional<Value> searchFiveConsecutiveValues(final Set<Value> values) {
if (values.size() < 5)
throw new RuntimeException("Programming error: trying to find a straight with less than five card values");
int consecutiveCardsCount = 0;
for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) {
final Value value = Value.values()[i];
if (values.contains(value))
++consecutiveCardsCount;
else
consecutiveCardsCount = 0;
if (consecutiveCardsCount == 5)
return Optional.of(Value.values()[i + 4]);
}
if (consecutiveCardsCount == 4)
if (values.contains(ACE))
return Optional.of(Value.FIVE);
return Optional.empty();
}
}
|
package org.jetel.graph.runtime;
import java.io.Serializable;
public class RestJobOutputData implements Serializable {
private static final long serialVersionUID = 8429131100028818807L;
private String contextUrl;
private String fileUrl;
private String contentType;
private String encoding;
private boolean attachment;
public RestJobOutputData(String contextUrl, String fileUrl, String contentType, String encoding, boolean attachment) {
this.contextUrl = contextUrl;
this.fileUrl = fileUrl;
this.contentType = contentType;
this.encoding = encoding;
this.attachment = attachment;
}
public String getContextUrl() {
return contextUrl;
}
public String getFileUrl() {
return fileUrl;
}
public String getContentType() {
return contentType;
}
public String getEncoding() {
return encoding;
}
public boolean isAttachment() {
return attachment;
}
}
|
package com.github.nsnjson;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.nsnjson.decoding.*;
import com.github.nsnjson.encoding.*;
import java.util.Optional;
/**
* NSNJSON Driver.
*/
public class Driver {
/**
* Encodes JSON to NSNJSON presentation.
* @see Encoder#encode(JsonNode)
* @param data any JSON data
* @return NSNJSON presentation of JSON
*/
public static Optional<JsonNode> encode(JsonNode data) {
return Encoder.encode(data);
}
/**
* Encodes JSON to NSNJSON presentation by custom encoding.
* @see Encoder#encode(JsonNode, Encoding)
* @param data any JSON data
* @return NSNJSON presentation of JSON
*/
public static Optional<JsonNode> encode(JsonNode data, Encoding encoding) {
return Encoder.encode(data, encoding);
}
public static Optional<JsonNode> encodeWithArrayStyle(JsonNode data) {
return Encoder.encodeWithArrayStyle(data);
}
/**
* Decodes JSON from specified NSNJSON presentation.
* @see Decoder#decode(JsonNode)
* @param presentation NSNJSON presentation of JSON
* @return JSON
*/
public static Optional<JsonNode> decode(JsonNode presentation) {
return Decoder.decode(presentation);
}
/**
* Decodes JSON from specified NSNJSON presentation by custom decoding.
* @see Decoder#decode(JsonNode, Decoding)
* @param presentation NSNJSON presentation of JSON
* @param decoding custom decoding
* @return JSON
*/
public static Optional<JsonNode> decode(JsonNode presentation, Decoding decoding) {
return Decoder.decode(presentation, decoding);
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-07-05");
this.setApiVersion("17.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-08-21");
this.setApiVersion("14.5.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-11-09");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* Kaltura API session
*
* @param ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param responseProfile
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-05-19");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package crystal.client;
import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import org.apache.log4j.Logger;
import crystal.Constants;
import crystal.client.ConflictDaemon.ComputationListener;
import crystal.model.ConflictResult;
import crystal.model.DataSource;
import crystal.model.ConflictResult.ResultStatus;
import crystal.util.LSMRLogger;
import crystal.util.TimeUtility;
/**
* This is the UI that lives in the system tray (windows), title bar (OS X) or somewhere else (linux). It contains the
* menu options and provides a lightweight home for bringing up the ConflictClient UI.
*
* @author rtholmes
*/
public class ConflictSystemTray implements ComputationListener {
/**
* Conflict client UI.
*/
private ConflictClient _client;
private Logger _log = Logger.getLogger(this.getClass());
/**
* Main preference reference.
*/
private ClientPreferences _prefs;
/**
* Timer used for refreshing the results.
*/
private Timer _timer;
final private TrayIcon _trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
public ConflictSystemTray() {
_log.info("ConflictSystemTray - started at: " + TimeUtility.getCurrentLSMRDateString());
}
private MenuItem updateNowItem;
private CheckboxMenuItem daemonEnabledItem;
/**
* Create the tray icon and get it installed in the tray.
*/
private void createAndShowGUI() {
try {
_prefs = ClientPreferences.loadPreferencesFromXML();
if (_prefs != null) {
_log.info("Preferences loaded successfully.");
} else {
String msg = "Error loading preferences.";
System.err.println(msg);
_log.error(msg);
}
} catch (Exception e) {
String msg = "Error initializing ConflictClient. Please update your preference file ( " + ClientPreferences.CONFIG_PATH + " )";
System.err.println(msg);
_log.error(msg);
System.err.println(e.getMessage());
_log.error(e.getMessage());
quit(-1);
}
// Check the SystemTray support
if (!SystemTray.isSupported()) {
String msg = "SystemTray is not supported on this system";
System.err.println(msg);
_log.error(msg);
quit(-1);
}
final PopupMenu trayMenu = new PopupMenu();
// _trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
_trayIcon.setImage(createImage("images/16X16/greenp.png", ""));
final SystemTray tray = SystemTray.getSystemTray();
_trayIcon.setToolTip("ConflictClient");
// Create a popup menu components
MenuItem aboutItem = new MenuItem("About");
MenuItem preferencesItem = new MenuItem("Edit Configuration");
daemonEnabledItem = new CheckboxMenuItem("Daemon Enabled");
updateNowItem = new MenuItem("Update Now");
final MenuItem showClientItem = new MenuItem("Show Client");
// MenuItem editConfigurationItem = new MenuItem("Edit Configuration");
MenuItem exitItem = new MenuItem("Exit");
// Add components to popup menu
trayMenu.add(aboutItem);
trayMenu.addSeparator();
trayMenu.add(preferencesItem);
trayMenu.add(daemonEnabledItem);
trayMenu.addSeparator();
trayMenu.add(updateNowItem);
trayMenu.addSeparator();
trayMenu.add(showClientItem);
trayMenu.addSeparator();
trayMenu.add(exitItem);
_trayIcon.setPopupMenu(trayMenu);
// make sure the client is enabled by default
daemonEnabledItem.setState(true);
try {
tray.add(_trayIcon);
} catch (AWTException e) {
_log.error("TrayIcon could not be added.");
return;
}
_trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
_log.trace("Tray icon ActionEvent: " + ae.getActionCommand());
// doesn't work on OS X; it doesn't register double clicks on
// the tray
showClient();
}
});
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Built by Reid Holmes and Yuriy Brun. Contact brun@cs.washington.edu.");
}
});
updateNowItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_log.info("Update now manually selected.");
performCalculations();
}
});
preferencesItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (_client != null) {
_client.close();
_client = null;
}
showClientItem.setEnabled(false);
// either creates (if one did not exist) or displays an existing
// PreferencesGUIEditorFrame configuration editor.
PreferencesGUIEditorFrame.getPreferencesGUIEditorFrame(_prefs);
/* Yuriy: Old Preferences UI code by Reid. @deprecated.
ClientPreferencesUI cp = new ClientPreferencesUI(new ClientPreferencesUI.IPreferencesListener() {
@Override
public void preferencesChanged(ProjectPreferences preferences) {
// when the preferences are updated, show the
// client
// _prefs = preferences;
// NOTE: prefs UI broken by multiple project
// refactor
}
@Override
public void preferencesDialogClosed() {
showClientItem.setEnabled(true);
// NOTE: prefs UI broken by multiple project
// refactor
}
});
cp.createAndShowGUI();
*/
}
});
showClientItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showClient();
}
});
daemonEnabledItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb1Id = e.getStateChange();
if (cb1Id == ItemEvent.SELECTED) {
// daemon enabled
_log.info("ConflictDaemon enabled");
if (_timer != null) {
// do it
_timer.start();
} else {
createTimer();
}
} else {
// daemon disabled
_log.info("ConflictDaemon disabled");
if (_timer != null) {
_timer.stop();
_timer = null;
}
for (CalculateTask ct : tasks) {
_log.info("disabling ct of state: " + ct.getState());
ct.cancel(true);
}
update();
}
}
});
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(_trayIcon);
String msg = "ConflictClient exited successfully.";
System.out.println(msg);
_log.trace("Exit action selected");
quit(0);
}
});
ConflictDaemon.getInstance().addListener(this);
performCalculations();
}
/**
* Create the image to use in the tray.
*
* @param path
* @param description
* @return
*/
protected Image createImage(String path, String description) {
URL imageURL = ConflictSystemTray.class.getResource(path);
if (imageURL == null) {
_log.error("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
private void createTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
}
_timer = new Timer((int) Constants.TIMER_CONSTANT, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_log.info("Timer fired at: " + TimeUtility.getCurrentLSMRDateString());
// if (_client != null) {
// // get the client to nicely refresh its elements
// // _client.calculateConflicts();
// performCalculations();
// } else {
performCalculations();
}
});
_timer.setInitialDelay((int) Constants.TIMER_CONSTANT);
_timer.start();
long nextFire = System.currentTimeMillis() + _timer.getDelay();
_log.info("Timer created - will fire in: " + TimeUtility.msToHumanReadable(_timer.getInitialDelay()) + " (@ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date(nextFire)) + ")");
}
HashSet<CalculateTask> tasks = new HashSet<CalculateTask>();
long startCalculations = 0L;
/**
* Perform the conflict calculations
*/
private void performCalculations() {
if (tasks.size() > 0) {
for (CalculateTask ct : tasks) {
_log.trace("CT state: " + ct.getState());
}
throw new RuntimeException("PerformCalculations being called in error; tasks > 0");
}
updateNowItem.setLabel("Updating...");
updateNowItem.setEnabled(false);
startCalculations = System.currentTimeMillis();
for (ProjectPreferences projPref : _prefs.getProjectPreference()) {
for (final DataSource source : projPref.getDataSources()) {
final CalculateTask ct = new CalculateTask(source, projPref, this, _client);
tasks.add(ct);
ct.execute();
ct.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// NOTE: this is a poor hack; update() should be called by the handlers automatically, but it
// seems that when this call is made the CT's state isn't always DONE so it fails to clear the
// tasks vector correctly.
update();
}
});
}
}
}
private void quit(int status) {
_log.info("ConflictSystemTray exited - code: " + status + " at: " + TimeUtility.getCurrentLSMRDateString());
System.exit(status);
}
/**
* Show the client and set up the timer.
*/
private void showClient() {
_log.info("Show client requested");
if (_client != null) {
_client.show();
} else {
_client = new ConflictClient();
_client.createAndShowGUI(_prefs);
}
}
@Override
public void update() {
_log.trace("ConflictSystemTray::update()");
Iterator<CalculateTask> ctIterator = tasks.iterator();
if (ctIterator.hasNext()) {
CalculateTask ct = ctIterator.next();
_log.trace("Current state: " + ct.getState());
if (ct.isDone()) {
ctIterator.remove();
}
}
_log.trace("Task size in update: " + tasks.size());
if (tasks.size() == 0) {
if (daemonEnabledItem.getState()) {
long end = System.currentTimeMillis();
long delta = end - startCalculations;
_log.info("Computation took: " + TimeUtility.msToHumanReadable(delta));
Constants.TIMER_CONSTANT = delta * Constants.TIMER_MULTIPLIER;
createTimer();
}
updateNowItem.setEnabled(true);
updateNowItem.setLabel("Update now");
}
boolean anyGreen = false;
boolean anyPull = false;
boolean anyYellow = false;
boolean anyRed = false;
for (ConflictResult result : ConflictDaemon.getInstance().getResults()) {
if (result.getStatus().equals(ResultStatus.SAME)) {
anyGreen = true;
}
if (result.getStatus().equals(ResultStatus.MERGECLEAN)) {
anyPull = true;
}
if (result.getStatus().equals(ResultStatus.MERGECONFLICT)) {
anyRed = true;
}
if (result.getStatus().equals(ResultStatus.BEHIND)) {
anyYellow = true;
}
}
if (anyRed) {
// TODO: should flush old images
// _trayIcon.getImage().flush();
_trayIcon.setImage(createImage("images/16X16/redstatus.png", ""));
} else if (anyYellow) {
_trayIcon.setImage(createImage("images/16X16/yellowstatus.png", ""));
} else if (anyPull) {
_trayIcon.setImage(createImage("images/16X16/greenp.png", ""));
} else if (anyGreen) {
_trayIcon.setImage(createImage("images/16X16/greenstatus.png", ""));
}
if (_client != null) {
_client.update();
}
}
/**
* Main execution point.
*
* @param args
*/
public static void main(String[] args) {
LSMRLogger.startLog4J(Constants.QUIET_CONSOLE, true, Constants.LOG_LEVEL, System.getProperty("user.home"), ".conflictClientLog");
// UIManager.put("swing.boldMetal", Boolean.FALSE);
ConflictSystemTray cst = new ConflictSystemTray();
cst.createAndShowGUI();
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-11-13");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* Kaltura API session
*
* @param ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param responseProfile
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-08-17");
this.setApiVersion("18.12.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-10-11");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* Kaltura API session
*
* @param ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param responseProfile
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.intellij.openapi.wm.impl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowType;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import java.awt.*;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class WindowInfo implements Cloneable,JDOMExternalizable{
/**
* XML tag.
*/
@NonNls static final String TAG="window_info";
/**
* Default window weight.
*/
static final float DEFAULT_WEIGHT=.33f;
private boolean myActive;
private ToolWindowAnchor myAnchor;
private boolean myAutoHide;
/**
* Bounds of window in "floating" mode. It equals to <code>null</code> if
* floating bounds are undefined.
*/
private Rectangle myFloatingBounds;
private String myId;
private ToolWindowType myInternalType;
private ToolWindowType myType;
private boolean myVisible;
private float myWeight;
/**
* Defines order of tool window button inside the stripe.
* The default value is <code>-1</code>.
*/
private int myOrder;
@NonNls protected static final String ID_ATTR = "id";
@NonNls protected static final String ACTIVE_ATTR = "active";
@NonNls protected static final String ANCHOR_ATTR = "anchor";
@NonNls protected static final String AUTOHIDE_ATTR = "auto_hide";
@NonNls protected static final String INTERNAL_TYPE_ATTR = "internal_type";
@NonNls protected static final String TYPE_ATTR = "type";
@NonNls protected static final String VISIBLE_ATTR = "visible";
@NonNls protected static final String WEIGHT_ATTR = "weight";
@NonNls protected static final String ORDER_ATTR = "order";
@NonNls protected static final String X_ATTR = "x";
@NonNls protected static final String Y_ATTR = "y";
@NonNls protected static final String WIDTH_ATTR = "width";
@NonNls protected static final String HEIGHT_ATTR = "height";
/**
* Creates <code>WindowInfo</code> for tool window with wpecified <code>ID</code>.
*/
WindowInfo(final String id){
myActive=false;
myAnchor=ToolWindowAnchor.LEFT;
myAutoHide=false;
myFloatingBounds=null;
myId=id;
setType(ToolWindowType.DOCKED);
myVisible=false;
myWeight=DEFAULT_WEIGHT;
myOrder=-1;
}
/**
* Creates copy of <code>WindowInfo</code> object.
*/
@SuppressWarnings({"EmptyCatchBlock"})
public WindowInfo copy(){
WindowInfo info=null;
try{
info=(WindowInfo)clone();
if(myFloatingBounds!=null){
info.myFloatingBounds=(Rectangle)myFloatingBounds.clone();
}
}catch(CloneNotSupportedException ignored){}
return info;
}
/**
* Copies all data from the passed <code>WindowInfo</code> into itself.
*/
void copyFrom(final WindowInfo info){
myActive=info.myActive;
myAnchor=info.myAnchor;
myAutoHide=info.myAutoHide;
if(info.myFloatingBounds!=null){
myFloatingBounds=(Rectangle)info.myFloatingBounds.clone();
}else{
myFloatingBounds=null;
}
myId=info.myId;
myType=info.myType;
myInternalType=info.myInternalType;
myVisible=info.myVisible;
myWeight=info.myWeight;
myOrder=info.myOrder;
}
/**
* @return tool window's anchor in internal mode.
*/
ToolWindowAnchor getAnchor(){
return myAnchor;
}
/**
* @return bound of tool window in floating mode.
*/
Rectangle getFloatingBounds(){
return myFloatingBounds;
}
/**
* @return <code>ID</code> of the tool window.
*/
String getId(){
return myId;
}
/**
* @return type of the tool window in internal (docked or sliding) mode. Actually the tool
* window can be in floating mode, but this method has sense if you want to know what type
* tool window had when it was internal one. The method never returns <code>null</code>.
*/
ToolWindowType getInternalType(){
return myInternalType;
}
/**
* @return current type of tool window.
* @see com.intellij.openapi.wm.ToolWindowType#DOCKED
* @see com.intellij.openapi.wm.ToolWindowType#FLOATING
* @see com.intellij.openapi.wm.ToolWindowType#SLIDING
*/
ToolWindowType getType(){
return myType;
}
/**
* @return internal weight of tool window. "weigth" means how much of internal desktop
* area the tool window is occupied. The weight has sense if the tool window is docked or
* sliding.
*/
float getWeight(){
return myWeight;
}
public int getOrder(){
return myOrder;
}
public void setOrder(final int order){
myOrder=order;
}
boolean isActive(){
return myActive;
}
boolean isAutoHide(){
return myAutoHide;
}
boolean isDocked(){
return ToolWindowType.DOCKED==myType;
}
boolean isFloating(){
return ToolWindowType.FLOATING==myType;
}
boolean isSliding(){
return ToolWindowType.SLIDING==myType;
}
boolean isVisible(){
return myVisible;
}
private static ToolWindowType parseToolWindowType(final String text){
if(ToolWindowType.DOCKED.toString().equals(text)){
return ToolWindowType.DOCKED;
}else if(ToolWindowType.FLOATING.toString().equals(text)){
return ToolWindowType.FLOATING;
}else if(ToolWindowType.SLIDING.toString().equals(text)){
return ToolWindowType.SLIDING;
}else{
throw new IllegalArgumentException();
}
}
private static ToolWindowAnchor parseToolWindowAnchor(final String text){
if(ToolWindowAnchor.TOP.toString().equals(text)){
return ToolWindowAnchor.TOP;
}else if(ToolWindowAnchor.LEFT.toString().equals(text)){
return ToolWindowAnchor.LEFT;
}else if(ToolWindowAnchor.BOTTOM.toString().equals(text)){
return ToolWindowAnchor.BOTTOM;
}else if(ToolWindowAnchor.RIGHT.toString().equals(text)){
return ToolWindowAnchor.RIGHT;
}else{
throw new IllegalArgumentException();
}
}
@SuppressWarnings({"EmptyCatchBlock"})
public void readExternal(final Element element){
myId=element.getAttributeValue(ID_ATTR);
try{
myActive=Boolean.valueOf(element.getAttributeValue(ACTIVE_ATTR)).booleanValue();
}catch(NumberFormatException ignored){}
try{
myAnchor=WindowInfo.parseToolWindowAnchor(element.getAttributeValue(ANCHOR_ATTR));
}catch(IllegalArgumentException ignored){}
myAutoHide=Boolean.valueOf(element.getAttributeValue(AUTOHIDE_ATTR)).booleanValue();
try{
myInternalType=WindowInfo.parseToolWindowType(element.getAttributeValue(INTERNAL_TYPE_ATTR));
}catch(IllegalArgumentException ignored){}
try{
myType=parseToolWindowType(element.getAttributeValue(TYPE_ATTR));
}catch(IllegalArgumentException ignored){}
myVisible=Boolean.valueOf(element.getAttributeValue(VISIBLE_ATTR)).booleanValue();
try{
myWeight=Float.parseFloat(element.getAttributeValue(WEIGHT_ATTR));
}catch(NumberFormatException ignored){}
try{
myOrder=Integer.valueOf(element.getAttributeValue(ORDER_ATTR)).intValue();
}catch(NumberFormatException ignored){}
try{
myFloatingBounds=new Rectangle(
Integer.parseInt(element.getAttributeValue(X_ATTR)),
Integer.parseInt(element.getAttributeValue(Y_ATTR)),
Integer.parseInt(element.getAttributeValue(WIDTH_ATTR)),
Integer.parseInt(element.getAttributeValue(HEIGHT_ATTR))
);
}catch(NumberFormatException ignored){}
}
/**
* Sets new anchor.
*/
void setAnchor(final ToolWindowAnchor anchor){
if(anchor==null){
//noinspection HardCodedStringLiteral
throw new IllegalArgumentException("anchor cannot be null");
}
myAnchor=anchor;
}
void setActive(final boolean active){
myActive=active;
}
void setAutoHide(final boolean autoHide){
myAutoHide=autoHide;
}
void setFloatingBounds(final Rectangle floatingBounds){
myFloatingBounds=floatingBounds;
}
void setType(final ToolWindowType type){
if(type==null){
//noinspection HardCodedStringLiteral
throw new IllegalArgumentException("type cannot be null");
}
if(ToolWindowType.DOCKED==type||ToolWindowType.SLIDING==type){
myInternalType=type;
}
myType=type;
}
void setVisible(final boolean visible){
myVisible=visible;
}
/**
* Sets window weight and adjust it to [0..1] range if necessary.
*/
void setWeight(float weight){
if(weight<.0f){
weight=.0f;
}else if(weight>1.0f){
weight=1.0f;
}
myWeight=weight;
}
public void writeExternal(final Element element){
element.setAttribute(ID_ATTR,myId);
element.setAttribute(ACTIVE_ATTR,myActive?Boolean.TRUE.toString():Boolean.FALSE.toString());
element.setAttribute(ANCHOR_ATTR,myAnchor.toString());
element.setAttribute(AUTOHIDE_ATTR,myAutoHide?Boolean.TRUE.toString():Boolean.FALSE.toString());
element.setAttribute(INTERNAL_TYPE_ATTR,myInternalType.toString());
element.setAttribute(TYPE_ATTR,myType.toString());
element.setAttribute(VISIBLE_ATTR,myVisible?Boolean.TRUE.toString():Boolean.FALSE.toString());
element.setAttribute(WEIGHT_ATTR,Float.toString(myWeight));
element.setAttribute(ORDER_ATTR,Integer.toString(myOrder));
if(myFloatingBounds!=null){
element.setAttribute(X_ATTR,Integer.toString(myFloatingBounds.x));
element.setAttribute(Y_ATTR,Integer.toString(myFloatingBounds.y));
element.setAttribute(WIDTH_ATTR,Integer.toString(myFloatingBounds.width));
element.setAttribute(HEIGHT_ATTR,Integer.toString(myFloatingBounds.height));
}
}
public boolean equals(final Object obj){
if(!(obj instanceof WindowInfo)){
return false;
}
final WindowInfo info=(WindowInfo)obj;
if(
myActive!=info.myActive||
myAnchor!=info.myAnchor||
!myId.equals(info.myId)||
myAutoHide!=info.myAutoHide||
!Comparing.equal(myFloatingBounds,info.myFloatingBounds)||
myInternalType!=info.myInternalType||
myType!=info.myType||
myVisible!=info.myVisible||
myWeight!=info.myWeight||
myOrder!=info.myOrder
){
return false;
}else{
return true;
}
}
public int hashCode(){
return myAnchor.hashCode()+myId.hashCode()+myType.hashCode()+myOrder;
}
@SuppressWarnings({"HardCodedStringLiteral"})
public String toString(){
final StringBuffer buffer=new StringBuffer();
buffer.append(getClass().getName()).append('[');
buffer.append("myId=").append(myId).append("; ");
buffer.append("myVisible=").append(myVisible).append("; ");
buffer.append("myActive=").append(myActive).append("; ");
buffer.append("myAnchor=").append(myAnchor).append("; ");
buffer.append("myOrder=").append(myOrder).append("; ");
buffer.append("myAutoHide=").append(myAutoHide).append("; ");
buffer.append("myWeight=").append(myWeight).append("; ");
buffer.append("myType=").append(myType).append("; ");
buffer.append("myInternalType=").append(myInternalType).append("; ");
buffer.append("myFloatingBounds=").append(myFloatingBounds);
buffer.append(']');
return buffer.toString();
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-05-26");
this.setApiVersion("16.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package uk.co.uwcs.choob;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.AccessController;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import uk.co.uwcs.choob.modules.Modules;
import uk.co.uwcs.choob.support.ChoobException;
import uk.co.uwcs.choob.support.ChoobInvocationError;
import uk.co.uwcs.choob.support.ChoobNoSuchCallException;
import uk.co.uwcs.choob.support.ChoobNoSuchPluginException;
import uk.co.uwcs.choob.support.ChoobPermission;
import uk.co.uwcs.choob.support.HelpNotSpecifiedException;
import uk.co.uwcs.choob.support.IRCInterface;
import uk.co.uwcs.choob.support.NoSuchCommandException;
import uk.co.uwcs.choob.support.NoSuchPluginException;
import uk.co.uwcs.choob.support.events.Event;
import uk.co.uwcs.choob.support.events.Message;
/**
* Root class of a plugin manager
* @author bucko
*/
public abstract class ChoobPluginManager
{
static Modules mods;
static IRCInterface irc;
static Map<String,ChoobPluginManager> pluginMap;
static Map<String,List<String>> commands;
static List<ChoobPluginManager> pluginManagers;
static SpellDictionaryChoob phoneticCommands;
public ChoobPluginManager()
{
AccessController.checkPermission(new ChoobPermission("root"));
}
public final static void initialise(final Modules modules, final IRCInterface ircinter)
{
if (mods != null)
return;
mods = modules;
ChoobPluginManager.irc = ircinter;
pluginManagers = new LinkedList<ChoobPluginManager>();
pluginMap = new HashMap<String,ChoobPluginManager>();
commands = new HashMap<String,List<String>>();
File transFile = new File("share/en_phonet.dat");
if (!transFile.exists()) {
transFile = new File("../share/en_phonet.dat");
}
try
{
phoneticCommands = new SpellDictionaryChoob(transFile);
}
catch (final IOException e)
{
System.err.println("Could not load phonetics file: " + transFile);
throw new RuntimeException("Couldn't load phonetics file", e);
}
}
protected abstract Object createPlugin(String pluginName, URL fromLocation) throws ChoobException;
protected abstract void destroyPlugin(String pluginName);
public String[] getHelp(String pluginName, String commandName) throws NoSuchCommandException
{
throw new NoSuchCommandException(commandName);
}
public String[] getInfo(String pluginName) throws NoSuchPluginException
{
throw new NoSuchPluginException(pluginName);
}
/**
* (Re)loads a plugin from an URL and a plugin name. Note that in the case
* of reloading, the old plugin will be disposed of AFTER the new one is
* loaded.
* @param pluginName Class name of plugin.
* @param fromLocation URL from which to get the plugin's contents.
* @return true if the plugin was reloaded
* @throws Exception Thrown if there's a syntactical error in the plugin's source.
*/
public final boolean loadPlugin(final String pluginName, final URL fromLocation) throws ChoobException
{
AccessController.checkPermission(new ChoobPermission("plugin.load." + pluginName.toLowerCase()));
// Make sure we're ready to add commands.
if (commands.get(pluginName.toLowerCase()) == null)
commands.put(pluginName.toLowerCase(), new ArrayList<String>());
createPlugin(pluginName, fromLocation);
// Now plugin is loaded with no problems. Install it.
// XXX Possible problem with double loading here. Shouldn't matter,
// though.
ChoobPluginManager man;
synchronized(pluginMap)
{
man = pluginMap.remove(pluginName.toLowerCase());
pluginMap.put(pluginName.toLowerCase(), this);
}
synchronized(pluginManagers)
{
if (!pluginManagers.contains(this))
pluginManagers.add(this);
}
if (man != null && man != this)
man.destroyPlugin(pluginName);
// If man existed, so did the plugin.
return man != null;
}
public final void unloadPlugin(final String pluginName) throws ChoobNoSuchPluginException
{
AccessController.checkPermission(new ChoobPermission("plugin.unload." + pluginName.toLowerCase()));
ChoobPluginManager man;
synchronized(pluginMap)
{
man = pluginMap.remove(pluginName.toLowerCase());
}
if (man != null)
man.destroyPlugin(pluginName);
else
throw new ChoobNoSuchPluginException(pluginName, "UNLOAD");
}
/**
* Get a list of plugins.
*/
public final String[] plugins()
{
synchronized(pluginMap)
{
final Set<String> keys = pluginMap.keySet();
final String[] ret = new String[keys.size()];
return keys.toArray(ret);
}
}
/**
* Get a list of commands in a plugin.
*/
public final String[] commands(final String pluginName)
{
synchronized(commands)
{
final List<String> coms = commands.get(pluginName.toLowerCase());
if (coms == null)
return null;
final String[] ret = new String[coms.size()];
return coms.toArray(ret);
}
}
/**
* Adds a command to the internal database.
*/
public final void addCommand(final String pluginName, final String commandName)
{
synchronized(phoneticCommands)
{
if (pluginName != null)
phoneticCommands.addWord((pluginName + "." + commandName).toLowerCase());
else
phoneticCommands.removeWord(commandName.toLowerCase());
}
synchronized(commands)
{
if (pluginName != null)
commands.get(pluginName.toLowerCase()).add(commandName);
else
commands.get("").add(commandName);
}
}
/**
* Removes a command from the internal database.
*/
public final void removeCommand(final String pluginName, final String commandName)
{
synchronized(phoneticCommands)
{
if (pluginName != null)
phoneticCommands.removeWord((pluginName + "." + commandName).toLowerCase());
else
phoneticCommands.removeWord(commandName.toLowerCase());
}
synchronized(commands)
{
if (pluginName != null)
commands.get(pluginName.toLowerCase()).remove(commandName);
else
commands.get("").remove(commandName);
}
}
/**
* Remove a command from the internal database. Use the two parameter
* version in preference to this!
*/
public final void removeCommand(final String commandName)
{
final Matcher ma = Pattern.compile("(\\w+)\\.(\\w+)").matcher(commandName);
if (ma.matches())
removeCommand(ma.group(1), ma.group(2));
else
removeCommand(null, commandName);
}
/**
* Add a command to the internal database. Use the two parameter
* version in preference to this!
*/
public final void addCommand(final String commandName)
{
final Matcher ma = Pattern.compile("(\\w+)\\.(\\w+)").matcher(commandName);
if (ma.matches())
addCommand(ma.group(1), ma.group(2));
else
addCommand(null, commandName);
}
public final static ProtectionDomain getProtectionDomain( final String pluginName )
{
return mods.security.getProtectionDomain( pluginName );
}
// TODO make these return ChoobTask[], and implement a spawnCommand
// etc. method to queue the tasks.
/**
* Attempts to call a method in the plugin, triggered by a line from IRC.
* @param command Command to call.
* @param ev Message object from IRC.
*/
abstract public ChoobTask commandTask(String plugin, String command, Message ev);
/**
* Run an interval on the given plugin
*/
abstract public ChoobTask intervalTask(String pluginName, Object param);
/**
* Perform any event handling on the given Event.
* @param ev Event to pass along.
*/
abstract public List<ChoobTask> eventTasks(Event ev);
/**
* Run any filters on the given Message.
* @param ev Message to pass along.
*/
abstract public List<ChoobTask> filterTasks(Message ev);
/**
* Attempt to perform an API call on a contained plugin.
* @param APIName The name of the API call.
* @param params Params to pass through.
* @throws ChoobNoSuchCallException when the call didn't exist.
* @throws ChoobInvocationError when the call threw an exception.
*/
abstract public Object doAPI(String pluginName, String APIName, Object... params) throws ChoobNoSuchCallException;
/**
* Attempt to perform an API call on a contained plugin.
* @param prefix The prefix (ie. type) of call.
* @param genericName The name of the call.
* @param params Params to pass through.
* @throws ChoobNoSuchCallException when the call didn't exist.
* @throws ChoobInvocationError when the call threw an exception.
*/
abstract public Object doGeneric(String pluginName, String prefix, String genericName, Object... params) throws ChoobNoSuchCallException;
/**
* Get the description of a command specified in an annotation
* @param pluginName The plugin name the command is in.
* @param commandName The command name.
* @return The description.
* @throws uk.co.uwcs.choob.support.HelpNotSpecifiedException If the command was not annotated with help.
*/
public String getCommandDescription(String pluginName, String commandName) throws HelpNotSpecifiedException
{
throw new HelpNotSpecifiedException();
}
/**
* Get the parameters of a command specified in an annotation
* @param pluginName The plugin name the command is in.
* @param commandName The command name.
* @return The parameters.
* @throws uk.co.uwcs.choob.support.HelpNotSpecifiedException If the command was not annotated with help.
*/
public String getCommandParameters(String pluginName, String commandName) throws HelpNotSpecifiedException
{
throw new HelpNotSpecifiedException();
}
/**
* Get the parameter descriptions of a command specified in an annotation
* @param pluginName The plugin name the command is in.
* @param commandName The command name.
* @return The usage.
* @throws uk.co.uwcs.choob.support.HelpNotSpecifiedException If the command was not annotated with help.
*/
public String[] getCommandParameterDescriptions(String pluginName, String commandName) throws HelpNotSpecifiedException
{
throw new HelpNotSpecifiedException();
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-05-17");
this.setApiVersion("15.0.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package uk.org.ownage.dmdirc.ui;
import java.awt.Dimension;
import java.util.Date;
import javax.swing.JScrollBar;
import uk.org.ownage.dmdirc.Server;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import uk.org.ownage.dmdirc.commandparser.CommandParser;
import uk.org.ownage.dmdirc.commandparser.CommandWindow;
import uk.org.ownage.dmdirc.logger.ErrorLevel;
import uk.org.ownage.dmdirc.logger.Logger;
import uk.org.ownage.dmdirc.ui.messages.Formatter;
import uk.org.ownage.dmdirc.ui.messages.Styliser;
/**
* The ServerFrame is the MDI window that shows server messages to the user
* @author chris
*/
public class ServerFrame extends javax.swing.JInternalFrame implements CommandWindow {
/**
* The border used when the frame is not maximised
*/
private Border myborder;
/**
* The dimensions of the titlebar of the frame
**/
private Dimension titlebarSize;
/**
* whether to auto scroll the textarea when adding text
*/
private boolean autoScroll = true;
/**
* holds the scrollbar for the frame
*/
private JScrollBar scrollBar;
private CommandParser commandParser;
/**
* Creates a new ServerFrame
* @param commandParser The command parser to use
*/
public ServerFrame(CommandParser commandParser) {
initComponents();
setFrameIcon(MainFrame.getMainFrame().getIcon());
setMaximizable(true);
setClosable(true);
setVisible(true);
setResizable(true);
scrollBar = jScrollPane1.getVerticalScrollBar();
this.commandParser = commandParser;
jTextField1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
ServerFrame.this.commandParser.parseCommand(ServerFrame.this, jTextField1.getText());
} catch (Exception e) {
Logger.error(ErrorLevel.ERROR, e);
}
jTextField1.setText("");
}
});
addPropertyChangeListener("maximum", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
if (propertyChangeEvent.getNewValue().equals(Boolean.TRUE)) {
ServerFrame.this.myborder = getBorder();
ServerFrame.this.titlebarSize =
((BasicInternalFrameUI)getUI())
.getNorthPane().getPreferredSize();
((BasicInternalFrameUI)getUI()).getNorthPane()
.setPreferredSize(new Dimension(0,0));
setBorder(new EmptyBorder(0,0,0,0));
MainFrame.getMainFrame().setMaximised(true);
} else {
autoScroll = ((scrollBar.getValue() + scrollBar.getVisibleAmount())
!= scrollBar.getMaximum());
if(autoScroll) {
jTextPane1.setCaretPosition(jTextPane1.getStyledDocument().getLength());
}
setBorder(ServerFrame.this.myborder);
((BasicInternalFrameUI)getUI()).getNorthPane()
.setPreferredSize(ServerFrame.this.titlebarSize);
MainFrame.getMainFrame().setMaximised(false);
}
}
});
}
/**
* Adds a line of text to the main text area, and scrolls the text pane
* down so that it's visible if the scrollbar is already at the bottom
* @param line text to add
*/
public void addLine(String line) {
String ts = Formatter.formatMessage("timestamp", new Date());
Styliser.addStyledString(jTextPane1.getStyledDocument(), ts+line+"\n");
autoScroll = ((scrollBar.getValue() + scrollBar.getVisibleAmount())
!= scrollBar.getMaximum());
if(autoScroll) {
jTextPane1.setCaretPosition(jTextPane1.getStyledDocument().getLength());
}
}
/**
* Formats the arguments using the Formatter, then adds the result to the
* main text area
* @param messageType The type of this message
* @param args The arguments for the message
*/
public void addLine(String messageType, Object... args) {
addLine(Formatter.formatMessage(messageType, args));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setTitle("Server Frame");
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextPane1.setEditable(false);
jScrollPane1.setViewportView(jTextPane1);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
}
|
package unluac.decompile;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import unluac.decompile.block.AlwaysLoop;
import unluac.decompile.block.Block;
import unluac.decompile.block.Break;
import unluac.decompile.block.ForBlock;
import unluac.decompile.block.NewElseEndBlock;
import unluac.decompile.block.NewIfThenElseBlock;
import unluac.decompile.block.NewIfThenEndBlock;
import unluac.decompile.block.NewRepeatBlock;
import unluac.decompile.block.NewSetBlock;
import unluac.decompile.block.NewWhileBlock;
import unluac.decompile.block.OuterBlock;
import unluac.decompile.block.TForBlock;
import unluac.decompile.condition.AndCondition;
import unluac.decompile.condition.BinaryCondition;
import unluac.decompile.condition.Condition;
import unluac.decompile.condition.OrCondition;
import unluac.decompile.condition.RegisterSetCondition;
import unluac.decompile.condition.SetCondition;
import unluac.decompile.condition.TestCondition;
import unluac.parse.LFunction;
public class ControlFlowHandler {
public static boolean verbose = false;
private static class Branch implements Comparable<Branch> {
private static enum Type {
comparison,
//comparisonset,
test,
testset,
finalset,
jump;
}
public Branch previous;
public Branch next;
public int line;
public int target;
public Type type;
public Condition cond;
public int targetFirst;
public int targetSecond;
public boolean inverseValue;
public Branch(int line, Type type, Condition cond, int targetFirst, int targetSecond) {
this.line = line;
this.type = type;
this.cond = cond;
this.targetFirst = targetFirst;
this.targetSecond = targetSecond;
this.inverseValue = false;
this.target = -1;
}
@Override
public int compareTo(Branch other) {
return this.line - other.line;
}
}
private static class State {
public LFunction function;
public Registers r;
public Code code;
public Branch begin_branch;
public Branch end_branch;
public Branch[] branches;
public boolean[] reverse_targets;
public List<Block> blocks;
}
public static List<Block> process(Decompiler d, Registers r) {
State state = new State();
state.function = d.function;
state.r = r;
state.code = d.code;
find_reverse_targets(state);
find_branches(state);
combine_branches(state);
initialize_blocks(state);
find_fixed_blocks(state);
find_while_loops(state);
find_repeat_loops(state);
find_break_statements(state);
unredirect_branches(state);
find_blocks(state);
// DEBUG: print branches stuff
/*
Branch b = state.begin_branch;
while(b != null) {
System.out.println("Branch at " + b.line);
System.out.println("\tcondition: " + b.cond);
b = b.next;
}
*/
return state.blocks;
}
private static void find_reverse_targets(State state) {
Code code = state.code;
boolean[] reverse_targets = state.reverse_targets = new boolean[state.code.length];
for(int line = 1; line <= code.length; line++) {
if(code.op(line) == Op.JMP) {
int target = code.target(line);
if(target <= line) {
reverse_targets[target] = true;
}
}
}
}
private static int find_loadboolblock(State state, int target) {
int loadboolblock = -1;
if(state.code.op(target) == Op.LOADBOOL) {
if(state.code.C(target) != 0) {
loadboolblock = target;
} else if(target - 1 >= 1 && state.code.op(target - 1) == Op.LOADBOOL && state.code.C(target - 1) != 0) {
loadboolblock = target - 1;
}
}
return loadboolblock;
}
private static void handle_loadboolblock(State state, boolean[] skip, int loadboolblock, Condition c, int line, int target) {
int loadboolvalue = state.code.B(target);
int final_line = -1;
if(loadboolblock - 1 >= 1 && state.code.op(loadboolblock - 1) == Op.JMP && state.code.target(loadboolblock - 1) == loadboolblock + 2) {
skip[loadboolblock - 1] = true;
final_line = loadboolblock - 2;
}
boolean inverse = false;
if(loadboolvalue == 1) {
inverse = true;
c = c.inverse();
}
Branch b;
if(line + 2 == loadboolblock) {
b = new Branch(line, Branch.Type.finalset, c, line + 2, loadboolblock + 2);
} else {
b = new Branch(line, Branch.Type.testset, c, line + 2, loadboolblock + 2);
}
b.target = state.code.A(loadboolblock);
b.inverseValue = inverse;
insert_branch(state, b);
if(final_line >= line + 2 && state.branches[final_line] == null) {
c = new SetCondition(final_line, get_target(state, final_line));
b = new Branch(final_line, Branch.Type.finalset, c, final_line, loadboolblock + 2);
b.target = state.code.A(loadboolblock);
insert_branch(state, b);
}
}
private static void find_branches(State state) {
Code code = state.code;
state.branches = new Branch[state.code.length + 1];
boolean[] skip = new boolean[code.length + 1];
for(int line = 1; line <= code.length; line++) {
if(!skip[line]) {
switch(code.op(line)) {
case EQ:
case LT:
case LE: {
BinaryCondition.Operator op = BinaryCondition.Operator.EQ;
if(code.op(line) == Op.LT) op = BinaryCondition.Operator.LT;
if(code.op(line) == Op.LE) op = BinaryCondition.Operator.LE;
int left = code.B(line);
int right = code.C(line);
int target = code.target(line + 1);
Condition c = new BinaryCondition(op, line, left, right);
if(code.A(line) == 1) {
c = c.inverse();
}
int loadboolblock = find_loadboolblock(state, target);
if(loadboolblock >= 1) {
handle_loadboolblock(state, skip, loadboolblock, c, line, target);
} else {
Branch b = new Branch(line, Branch.Type.comparison, c, line + 2, target);
if(code.A(line) == 1) {
b.inverseValue = true;
}
insert_branch(state, b);
}
skip[line + 1] = true;
break;
}
case TEST: {
Condition c = new TestCondition(line, code.A(line));
if(code.C(line) != 0) c = c.inverse();
int target = code.target(line + 1);
int loadboolblock = find_loadboolblock(state, target);
if(loadboolblock >= 1) {
handle_loadboolblock(state, skip, loadboolblock, c, line, target);
} else {
Branch b = new Branch(line, Branch.Type.test, c, line + 2, target);
b.target = code.A(line);
if(code.C(line) != 0) b.inverseValue = true;
insert_branch(state, b);
}
skip[line + 1] = true;
break;
}
case TESTSET: {
Condition c = new TestCondition(line, code.B(line));
int target = code.target(line + 1);
Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target);
b.target = code.A(line);
if(code.C(line) != 0) b.inverseValue = true;
skip[line + 1] = true;
insert_branch(state, b);
int final_line = target - 1;
if(state.branches[final_line] == null) {
int loadboolblock = find_loadboolblock(state, target - 2);
if(loadboolblock == -1) {
if(line + 2 == target) {
c = new RegisterSetCondition(line, get_target(state, line));
//c = new SetCondition(line - 1, get_target(state, line));
final_line = final_line + 1;
} else {
c = new SetCondition(final_line, get_target(state, final_line));
}
b = new Branch(final_line, Branch.Type.finalset, c, target, target);
b.target = code.A(line);
insert_branch(state, b);
}
}
break;
}
case JMP: {
int target = code.target(line);
Branch b = new Branch(line, Branch.Type.jump, null, target, target);
insert_branch(state, b);
break;
}
}
}
}
link_branches(state);
}
private static void combine_branches(State state) {
Branch b;
b = state.end_branch;
while(b != null) {
b = combine_left(state, b).previous;
}
/*
b = state.end_branch;
while(b != null) {
Branch result = combine_right(state, b);
if(result != null) {
b = result;
if(b.next != null) {
b = b.next;
}
} else {
b = b.previous;
}
}
*/
}
private static void unredirect_branches(State state) {
// There is more complication here
int[] redirect = new int[state.code.length + 1];
Branch b = state.end_branch;
while(b != null) {
if(b.type == Branch.Type.jump) {
if(redirect[b.targetFirst] == 0) {
redirect[b.targetFirst] = b.line;
} else {
int temp = b.targetFirst;
b.targetFirst = b.targetSecond = redirect[temp];
redirect[temp] = b.line;
}
}
b = b.previous;
}
b = state.begin_branch;
while(b != null) {
if(b.type != Branch.Type.jump) {
if(redirect[b.targetSecond] != 0) {
// Hack-ish -- redirect can't extend the scope
boolean skip = false;
if(b.targetSecond > b.line & redirect[b.targetSecond] > b.targetSecond) skip = true;
if(!skip) {
//System.out.println("Redirected to " + redirct[b.targetSecond] + " from " + b.targetSecond);
//if(redirect[b.targetSecond] < b.targetSecond)
b.targetSecond = redirect[b.targetSecond];
}
}
}
b = b.next;
}
}
private static void initialize_blocks(State state) {
state.blocks = new LinkedList<Block>();
}
private static void find_fixed_blocks(State state) {
List<Block> blocks = state.blocks;
Registers r = state.r;
Code code = state.code;
Op tforTarget = state.function.header.version.getTForTarget();
blocks.add(new OuterBlock(state.function, state.code.length));
for(int line = 1; line <= code.length; line++) {
switch(code.op(line)) {
case JMP: {
int target = code.target(line);
if(code.op(target) == tforTarget) {
int A = code.A(target);
int C = code.C(target);
if(C == 0) throw new IllegalStateException();
r.setInternalLoopVariable(A, target, line + 1); //TODO: end?
r.setInternalLoopVariable(A + 1, target, line + 1);
r.setInternalLoopVariable(A + 2, target, line + 1);
for(int index = 1; index <= C; index++) {
r.setExplicitLoopVariable(A + 2 + index, line, target + 2); //TODO: end?
}
remove_branch(state, state.branches[line]);
remove_branch(state, state.branches[target + 1]);
blocks.add(new TForBlock(state.function, line + 1, target + 2, A, C, r));
}
break;
}
case FORPREP: {
int target = code.target(line);
blocks.add(new ForBlock(state.function, line + 1, target + 1, code.A(line), r));
r.setInternalLoopVariable(code.A(line), line, target + 1);
r.setInternalLoopVariable(code.A(line) + 1, line, target + 1);
r.setInternalLoopVariable(code.A(line) + 2, line, target + 1);
r.setExplicitLoopVariable(code.A(line) + 3, line, target + 1);
break;
}
}
}
}
private static void unredirect(State state, int begin, int end, int line, int target) {
Branch b = state.begin_branch;
while(b != null) {
if(b.line >= begin && b.line < end && b.targetSecond == target) {
b.targetSecond = line;
}
b = b.next;
}
}
private static void find_while_loops(State state) {
List<Block> blocks = state.blocks;
Registers r = state.r;
Code code = state.code;
Branch[] whileEnds = new Branch[code.length + 1];
Branch b = state.begin_branch;
while(b != null) {
if(b.type == Branch.Type.jump) {
if(b.targetFirst < b.line) {
whileEnds[b.targetFirst] = b;
}
}
b = b.next;
}
for(int line = 1; line <= code.length; line++) {
Branch j = whileEnds[line];
if(j != null) {
int loopback = line;
int end = j.line + 1;
b = state.begin_branch;
while(b != null) {
if(is_conditional(b) && b.line >= loopback && b.line < j.line && b.targetSecond == end) {
break;
}
b = b.next;
}
Block loop;
if(b != null) {
remove_branch(state, b);
loop = new NewWhileBlock(state.function, r, b.cond, b.targetFirst, b.targetSecond);
unredirect(state, loopback, end, j.line, loopback);
} else {
loop = new AlwaysLoop(state.function, loopback, end);
unredirect(state, loopback, end, j.line, loopback);
}
remove_branch(state, j);
blocks.add(loop);
}
}
}
private static void find_repeat_loops(State state) {
List<Block> blocks = state.blocks;
Branch b = state.begin_branch;
while(b != null) {
if(is_conditional(b)) {
if(b.targetSecond < b.targetFirst) {
Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst);
remove_branch(state, b);
blocks.add(block);
}
}
b = b.next;
}
}
private static void unredirect_break(State state, int line, Block enclosing) {
Branch b = state.begin_branch;
while(b != null) {
if(is_conditional(b) && enclosing.contains(b.line) && b.targetFirst <= line && b.targetSecond == enclosing.end) {
b.targetSecond = line;
}
b = b.next;
}
}
private static void find_break_statements(State state) {
List<Block> blocks = state.blocks;
Branch b = state.begin_branch;
while(b != null) {
if(b.type == Branch.Type.jump) {
int line = b.line;
Block enclosing = null;
for(Block block : blocks) {
if(block.contains(line) && block.breakable()) {
if(enclosing == null || enclosing.contains(block)) {
enclosing = block;
}
}
}
if(enclosing != null && b.targetFirst == enclosing.end) {
Block block = new Break(state.function, b.line, b.targetFirst);
remove_branch(state, b);
unredirect_break(state, line, enclosing);
blocks.add(block);
}
}
b = b.next;
}
//TODO: conditional breaks (Lua 5.2) [conflicts with unredirection]
}
private static void find_blocks(State state) {
List<Block> blocks = state.blocks;
Code code = state.code;
Branch b = state.begin_branch;
while(b != null) {
if(is_conditional(b)) {
// Conditional branches decompile to if, while, or repeat
boolean has_tail = false;
int tail_line = b.targetSecond - 1;
int tail_target = 0;
if(tail_line >= 1 && code.op(tail_line) == Op.JMP) {
Branch tail_branch = state.branches[tail_line];
if(tail_branch != null && tail_branch.type == Branch.Type.jump) {
has_tail = true;
tail_target = tail_branch.targetFirst;
}
}
if(b.targetSecond > b.targetFirst) {
if(has_tail) {
if(tail_target > tail_line) {
// If -- then -- else
//System.out.println("If -- then -- else");
//System.out.println("\t" + b.line + "\t" + b.cond.toString());
NewIfThenElseBlock block = new NewIfThenElseBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond);
NewElseEndBlock block2 = new NewElseEndBlock(state.function, b.targetSecond, tail_target);
block.partner = block2;
block2.partner = block;
//System.out.println("else -- end " + block2.begin + " " + block2.end);
remove_branch(state, state.branches[tail_line]);
blocks.add(block);
blocks.add(block2);
} else {
if(tail_target <= b.line) {
// While
//System.out.println("While");
//System.out.println("\t" + b.line + "\t" + b.cond.toString());
Block block = new NewWhileBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond);
blocks.add(block);
} else {
// If -- then (tail is from an inner loop)
//System.out.println("If -- then");
//System.out.println("\t" + b.line + "\t" + b.cond.toString());
Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond);
blocks.add(block);
}
}
} else {
// If -- then
//System.out.println("If -- then");
//System.out.println("\t" + b.line + "\t" + b.cond.toString() + "\t" + b.targetFirst + "\t" + b.targetSecond);
Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond);
blocks.add(block);
}
} else {
// Repeat
//System.out.println("Repeat " + b.targetSecond + " .. " + b.targetFirst);
//System.out.println("\t" + b.line + "\t" + b.cond.toString());
Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst);
blocks.add(block);
}
} else if(is_assignment(b) || b.type == Branch.Type.finalset) {
Block block = new NewSetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, false, state.r);
blocks.add(block);
//System.out.println("Assign block " + b.line);
} else if(b.type == Branch.Type.jump) {
Block block = new Break(state.function, b.line, b.targetFirst);
blocks.add(block);
}
b = b.next;
}
Collections.sort(blocks);
}
private static boolean is_conditional(Branch b) {
return b.type == Branch.Type.comparison || b.type == Branch.Type.test;
}
private static boolean is_conditional(Branch b, int r) {
return b.type == Branch.Type.comparison || b.type == Branch.Type.test && b.target != r;
}
private static boolean is_assignment(Branch b) {
return b.type == Branch.Type.testset;
}
private static boolean is_assignment(Branch b, int r) {
return b.type == Branch.Type.testset || b.type == Branch.Type.test && b.target == r;
}
private static boolean adjacent(State state, Branch branch0, Branch branch1) {
if(branch0 == null || branch1 == null) {
return false;
} else {
boolean adjacent = branch0.targetFirst <= branch1.line;
if(adjacent) {
for(int line = branch0.targetFirst; line < branch1.line; line++) {
if(is_statement(state, line)) {
if(verbose) System.out.println("Found statement at " + line + " between " + branch0.line + " and " + branch1.line);
adjacent = false;
break;
}
}
adjacent = adjacent && !state.reverse_targets[branch1.line];
}
return adjacent;
}
}
private static Branch combine_left(State state, Branch branch1) {
if(is_conditional(branch1)) {
return combine_conditional(state, branch1);
} else {
return combine_assignment(state, branch1);
}
}
private static Branch combine_conditional(State state, Branch branch1) {
Branch branch0 = branch1.previous;
if(adjacent(state, branch0, branch1) && is_conditional(branch0) && is_conditional(branch1)) {
if(branch0.targetSecond == branch1.targetFirst) {
// Combination if not branch0 or branch1 then
branch0 = combine_conditional(state, branch0);
Condition c = new OrCondition(branch0.cond.inverse(), branch1.cond);
Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond);
branchn.inverseValue = branch1.inverseValue;
if(verbose) System.err.println("conditional or " + branchn.line);
replace_branch(state, branch0, branch1, branchn);
return combine_conditional(state, branchn);
} else if(branch0.targetSecond == branch1.targetSecond) {
// Combination if branch0 and branch1 then
branch0 = combine_conditional(state, branch0);
Condition c = new AndCondition(branch0.cond, branch1.cond);
Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond);
branchn.inverseValue = branch1.inverseValue;
if(verbose) System.err.println("conditional and " + branchn.line);
replace_branch(state, branch0, branch1, branchn);
return combine_conditional(state, branchn);
}
}
return branch1;
}
private static Branch combine_assignment(State state, Branch branch1) {
Branch branch0 = branch1.previous;
if(adjacent(state, branch0, branch1)) {
int register = branch1.target;
//System.err.println("blah " + branch1.line + " " + branch0.line);
if(is_conditional(branch0) && is_assignment(branch1)) {
//System.err.println("bridge cand " + branch1.line + " " + branch0.line);
if(branch0.targetSecond == branch1.targetFirst) {
boolean inverse = branch0.inverseValue;
if(verbose) System.err.println("bridge " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line);
branch0 = combine_conditional(state, branch0);
if(inverse != branch0.inverseValue) throw new IllegalStateException();
Condition c;
if(inverse) {
//System.err.println("bridge or " + branch0.line + " " + branch0.inverseValue);
c = new OrCondition(branch0.cond.inverse(), branch1.cond);
} else {
//System.err.println("bridge and " + branch0.line + " " + branch0.inverseValue);
c = new AndCondition(branch0.cond, branch1.cond);
}
Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond);
branchn.inverseValue = branch1.inverseValue;
branchn.target = register;
replace_branch(state, branch0, branch1, branchn);
return combine_assignment(state, branchn);
} else if(branch0.targetSecond == branch1.targetSecond) {
/*
Condition c = new AndCondition(branch0.cond, branch1.cond);
Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond);
replace_branch(state, branch0, branch1, branchn);
return branchn;
*/
}
}
if(is_assignment(branch0, register) && is_assignment(branch1) && branch0.inverseValue == branch1.inverseValue) {
if(branch0.type == Branch.Type.test && branch0.inverseValue) {
branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it
}
if(branch0.targetSecond == branch1.targetSecond) {
Condition c;
//System.err.println("preassign " + branch1.line + " " + branch0.line + " " + branch0.targetSecond);
boolean inverse = branch0.inverseValue;
if(verbose) System.err.println("assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line);
branch0 = combine_assignment(state, branch0);
if(inverse != branch0.inverseValue) throw new IllegalStateException();
if(branch0.inverseValue) {
//System.err.println("assign and " + branch1.line + " " + branch0.line);
c = new OrCondition(branch0.cond, branch1.cond);
} else {
//System.err.println("assign or " + branch1.line + " " + branch0.line);
c = new AndCondition(branch0.cond, branch1.cond);
}
Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond);
branchn.inverseValue = branch1.inverseValue;
branchn.target = register;
replace_branch(state, branch0, branch1, branchn);
return combine_assignment(state, branchn);
}
}
if(is_assignment(branch0, register) && branch1.type == Branch.Type.finalset) {
if(branch0.targetSecond == branch1.targetSecond) {
if(branch0.type == Branch.Type.test && branch0.inverseValue) {
branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it
}
Condition c;
//System.err.println("final preassign " + branch1.line + " " + branch0.line);
boolean inverse = branch0.inverseValue;
if(verbose) System.err.println("final assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line);
branch0 = combine_assignment(state, branch0);
if(inverse != branch0.inverseValue) throw new IllegalStateException();
if(branch0.inverseValue) {
//System.err.println("final assign or " + branch1.line + " " + branch0.line);
c = new OrCondition(branch0.cond, branch1.cond);
} else {
//System.err.println("final assign and " + branch1.line + " " + branch0.line);
c = new AndCondition(branch0.cond, branch1.cond);
}
Branch branchn = new Branch(branch0.line, Branch.Type.finalset, c, branch1.targetFirst, branch1.targetSecond);
branchn.target = register;
replace_branch(state, branch0, branch1, branchn);
return combine_assignment(state, branchn);
}
}
}
return branch1;
}
private static void replace_branch(State state, Branch branch0, Branch branch1, Branch branchn) {
state.branches[branch0.line] = null;
state.branches[branch1.line] = null;
branchn.previous = branch0.previous;
if(branchn.previous == null) {
state.begin_branch = branchn;
} else {
branchn.previous.next = branchn;
}
branchn.next = branch1.next;
if(branchn.next == null) {
state.end_branch = branchn;
} else {
branchn.next.previous = branchn;
}
state.branches[branchn.line] = branchn;
}
private static void remove_branch(State state, Branch b) {
state.branches[b.line] = null;
Branch prev = b.previous;
Branch next = b.next;
if(prev != null) {
prev.next = next;
} else {
state.begin_branch = next;
}
if(next != null) {
next.previous = prev;
} else {
state.end_branch = next;
}
}
private static void insert_branch(State state, Branch b) {
state.branches[b.line] = b;
}
private static void link_branches(State state) {
Branch previous = null;
for(int index = 0; index < state.branches.length; index++) {
Branch b = state.branches[index];
if(b != null) {
b.previous = previous;
if(previous != null) {
previous.next = b;
} else {
state.begin_branch = b;
}
previous = b;
}
}
state.end_branch = previous;
}
/**
* Returns the target register of the instruction at the given
* line or -1 if the instruction does not have a unique target.
*
* TODO: this probably needs a more careful pass
*/
private static int get_target(State state, int line) {
Code code = state.code;
switch(code.op(line)) {
case MOVE:
case LOADK:
case LOADBOOL:
case GETUPVAL:
case GETTABUP:
case GETGLOBAL:
case GETTABLE:
case NEWTABLE:
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
case POW:
case UNM:
case NOT:
case LEN:
case CONCAT:
case CLOSURE:
case TESTSET:
return code.A(line);
case LOADNIL:
if(code.A(line) == code.B(line)) {
return code.A(line);
} else {
return -1;
}
case SETGLOBAL:
case SETUPVAL:
case SETTABUP:
case SETTABLE:
case JMP:
case TAILCALL:
case RETURN:
case FORLOOP:
case FORPREP:
case TFORCALL:
case TFORLOOP:
case CLOSE:
return -1;
case SELF:
return -1;
case EQ:
case LT:
case LE:
case TEST:
case SETLIST:
return -1;
case CALL: {
int a = code.A(line);
int c = code.C(line);
if(c == 2) {
return a;
} else {
return -1;
}
}
case VARARG: {
int a = code.A(line);
int b = code.B(line);
if(b == 1) {
return a;
} else {
return -1;
}
}
default:
throw new IllegalStateException();
}
}
private static boolean is_statement(State state, int line) {
if(state.reverse_targets[line]) return true;
Registers r = state.r;
int testRegister = -1;
Code code = state.code;
switch(code.op(line)) {
case MOVE:
case LOADK:
case LOADBOOL:
case GETUPVAL:
case GETTABUP:
case GETGLOBAL:
case GETTABLE:
case NEWTABLE:
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
case POW:
case UNM:
case NOT:
case LEN:
case CONCAT:
case CLOSURE:
return r.isLocal(code.A(line), line) || code.A(line) == testRegister;
case LOADNIL:
for(int register = code.A(line); register <= code.B(line); register++) {
if(r.isLocal(register, line)) {
return true;
}
}
return false;
case SETGLOBAL:
case SETUPVAL:
case SETTABUP:
case SETTABLE:
case JMP:
case TAILCALL:
case RETURN:
case FORLOOP:
case FORPREP:
case TFORCALL:
case TFORLOOP:
case CLOSE:
return true;
case SELF:
return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line);
case EQ:
case LT:
case LE:
case TEST:
case TESTSET:
case SETLIST:
return false;
case CALL: {
int a = code.A(line);
int c = code.C(line);
if(c == 1) {
return true;
}
if(c == 0) c = r.registers - a + 1;
for(int register = a; register < a + c - 1; register++) {
if(r.isLocal(register, line)) {
return true;
}
}
return (c == 2 && a == testRegister);
}
case VARARG: {
int a = code.A(line);
int b = code.B(line);
if(b == 0) b = r.registers - a + 1;
for(int register = a; register < a + b - 1; register++) {
if(r.isLocal(register, line)) {
return true;
}
}
return false;
}
default:
throw new IllegalStateException("Illegal opcode: " + code.op(line));
}
}
// static only
private ControlFlowHandler() {
}
}
|
package com.lynx.fsm;
import java.util.Collection;
import com.google.common.collect.Multimap;
/**
* Abstract state machine providing validation and configuration operations
*
* @author daniel.las
*
* @param <S>
* @param <C>
*/
public abstract class StateMachine<S extends StateType, C extends StateHolder<S>, X> implements Forwardable<S>,
ContextHolder<C>, BeanValidating, Secured, Configurable<S, C, X>, StateProvider<S>, ExecutionContextAware<X> {
S state;
C context;
Multimap<S, Transition<S, C, X>> transitions;
X executionContext;
@Override
public void forward() {
if (state.isFinal()) {
throw new StateMachineException("Machine is in FINAL state");
}
Collection<Transition<S, C, X>> possibleEnds = transitions.get(state);
Transition<S, C, X> resolvedTransition = null;
// There are no transitions for start state, no knowledge what to do
if (possibleEnds.isEmpty()) {
throw new StateMachineException(String.format("There are no transitions for start state %s", state));
}
// We have only one transition with given start
if (possibleEnds.size() == 1) {
resolvedTransition = possibleEnds.iterator().next();
// There is condition which must be met
if (resolvedTransition.getCondition() != null) {
// Condition is not met
if (!resolvedTransition.getCondition().check(resolvedTransition.getEnd(), context)) {
throw new StateMachineException(String.format("Condition for transition from %s to %s is not met",
state, resolvedTransition.getEnd()));
}
}
} else {
Transition<S, C, X> goodEnd = null;
for (Transition<S, C, X> end : possibleEnds) {
if (end.getCondition() == null) {
throw new StateMachineException(
String.format("There is no condition for possible transition from %s to %s. Decision can't be taken when no state is requested."));
}
if (end.getCondition().check(end.getEnd(), context)) {
// We already have good end so next state is ambiguous
if (goodEnd != null) {
throw new StateMachineException(
"There is more than one transition from state %s fullfilling condition");
}
goodEnd = end;
}
}
resolvedTransition = goodEnd;
}
// No transition fulfilling conditions found
if (resolvedTransition == null) {
throw new StateMachineException(String.format(
"No transition fulfilling confition found for start state %s ", state));
}
// state
if (resolvedTransition.getRoles() != null) {
checkPermissions(resolvedTransition.getRoles());
}
// Run action if executor is set
if (resolvedTransition.getBeforeAction() != null) {
resolvedTransition.getBeforeAction().execute(executionContext, context);
}
// Validation groups are set, process validation
if (resolvedTransition.getValidationGroups() != null) {
validate(resolvedTransition.getValidationGroups());
}
if (resolvedTransition.getValidator() != null) {
resolvedTransition.getValidator().validate(resolvedTransition.getEnd(), context);
}
// Everything passed, we are good to go,
state = resolvedTransition.getEnd();
context.setState(state);
// Run action if executor is set
if (resolvedTransition.getAfterAction() != null) {
resolvedTransition.getAfterAction().execute(executionContext, context);
}
}
@Override
public void forward(S requestedState) {
if (state.isFinal()) {
throw new StateMachineException("Machine is in FINAL state");
}
Collection<Transition<S, C, X>> possibleEnds = transitions.get(state);
Transition<S, C, X> resolvedTransition = null;
// There are no transitions for start state, no knowledge what to do
if (possibleEnds.isEmpty()) {
throw new StateMachineException(String.format("There are no transitions for start state %s", state));
}
// Find transition with end equals requestedState
for (Transition<S, C, X> end : possibleEnds) {
if (requestedState.equals(end.getEnd())) {
resolvedTransition = end;
}
}
// No transition found
if (resolvedTransition == null) {
throw new StateMachineException(String.format("No transition found for start state %s and end state %s",
state, requestedState));
}
// Good transition found, check condition if exists
if (resolvedTransition.getCondition() != null) {
if (!resolvedTransition.getCondition().check(requestedState, context)) {
throw new StateMachineException(String.format(
"No transition fulfilling confition found for start state %s and requested state %s", state,
requestedState));
}
}
// state
if (resolvedTransition.getRoles() != null) {
checkPermissions(resolvedTransition.getRoles());
}
// Run action if executor is set
if (resolvedTransition.getBeforeAction() != null) {
resolvedTransition.getBeforeAction().execute(executionContext, context);
}
// Validation groups are set, process Bean validation
if (resolvedTransition.getValidationGroups() != null) {
validate(resolvedTransition.getValidationGroups());
}
// Business validator is set, process business validation
if (resolvedTransition.getValidator() != null) {
resolvedTransition.getValidator().validate(requestedState, context);
}
// Everything passed, we are good to go,
state = resolvedTransition.getEnd();
context.setState(state);
// Run action if executor is set
if (resolvedTransition.getAfterAction() != null) {
resolvedTransition.getAfterAction().execute(executionContext, context);
}
}
@Override
public void setTransitions(Multimap<S, Transition<S, C, X>> transitions) {
this.transitions = transitions;
}
@Override
public void setContext(C context) {
this.context = context;
this.state = context.getState();
}
@Override
public C getContext() {
return context;
}
@Override
public S getState() {
return state;
}
@Override
public void setExecutionContext(X executionContext) {
this.executionContext = executionContext;
}
@Override
public abstract void validate(Class<?>... groups);
@Override
public abstract void checkPermissions(String... roles);
}
|
package com.vikram.web;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vikram.model.Expense;
import com.vikram.openidconnect.login.core.identity.Identity;
import com.vikram.util.Environment;
import com.vikram.util.TestIdentity;
@Controller
@RequestMapping("/newexpense")
public class NewExpense {
private static final String SERVICE_ENDPOINT = "http:
private static SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
@RequestMapping(method = RequestMethod.POST)
public ModelAndView addExpense(Identity user, Expense expense, HttpServletRequest request) {
if(Environment.isDevelopment(request)){
user = TestIdentity.get();
}
if(!user.isValid()){
RedirectView view = new RedirectView("/login",true);
return new ModelAndView(view);
}
invokeAddExpenseService(expense);
ModelAndView mv = new ModelAndView();
mv.addObject("useremail", user.getEmailAddress());
mv.addObject("expenseAdded",true);
mv.addObject("current_date", dateFormat.format(new Date()));
mv.setViewName("dashboard");
return mv;
}
private void invokeAddExpenseService(Expense expense) {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(SERVICE_ENDPOINT);
expense.setTags("sample tags");
try {
post.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(expense),ContentType.APPLICATION_JSON));
HttpResponse response = client.execute(post);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package controllers;
import com.neovisionaries.i18n.CountryCode;
import com.typesafe.config.ConfigFactory;
import org.junit.Before;
import org.junit.Test;
import play.Configuration;
import play.mvc.Http;
import testUtils.TestableRequestBuilder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static com.neovisionaries.i18n.CountryCode.ES;
import static com.neovisionaries.i18n.CountryCode.AT;
import static com.neovisionaries.i18n.CountryCode.UK;
public class SunriseControllerTest extends WithSunriseApplication {
private SunriseController controller;
@Before
public void setUp() {
controller = new SunriseController(null, null);
}
@Test
public void userCountryIsCountryFoundInCookie() {
List<Http.Cookie> cookies = Collections.singletonList(countryCookie("SHOP_COUNTRY", ES));
Http.Request request = new TestableRequestBuilder().cookies(cookies).build();
Configuration config = configuration(Collections.singletonMap("sphere.countries", Arrays.asList("AT")));
assertThat(controller.country(request, config)).isEqualTo(ES);
}
@Test
public void userCountryIsDefaultWhenNoCookieFound() {
Http.Request request = new TestableRequestBuilder().build();
Configuration config = configuration(Collections.singletonMap("sphere.countries", Arrays.asList("AT")));
assertThat(controller.country(request, config)).isEqualTo(AT);
}
@Test
public void availableCountriesSkipsInvalidCountryFromConfiguration() {
Configuration config = configuration(Collections.singletonMap("sphere.countries", Arrays.asList("INVALID","UK")));
assertThat(controller.availableCountries(config)).containsExactly(UK);
}
@Test
public void availableCountriesGetsAllCountriesFromConfiguration() {
Configuration config = configuration(Collections.singletonMap("sphere.countries", Arrays.asList("AT","UK")));
assertThat(controller.availableCountries(config)).containsExactly(AT, UK);
}
@Test
public void defaultCountryIsFirstCountryFromConfiguration() {
Configuration config = configuration(Collections.singletonMap("sphere.countries", Arrays.asList("AT","UK")));
assertThat(controller.defaultCountry(config)).isEqualTo(AT);
}
@Test(expected=RuntimeException.class)
public void defaultCountryThrowsExceptionWhenNoneConfigured() {
Configuration config = configuration(Collections.emptyMap());
controller.defaultCountry(config);
}
@Test
public void countryCookieNameIsNameFromConfiguration() {
Configuration config = configuration(Collections.singletonMap("shop.country.cookie", "ANOTHER_COOKIE_NAME"));
assertThat(controller.countryCookieName(config)).isEqualTo("ANOTHER_COOKIE_NAME");
}
@Test
public void countryCookieNameIsDefaultWhenNoneConfigured() {
Configuration config = configuration(Collections.emptyMap());
assertThat(controller.countryCookieName(config)).isEqualTo("SHOP_COUNTRY");
}
private Http.Cookie countryCookie(String name, CountryCode country) {
return new Http.Cookie(name, country.getAlpha2(), null, null, null, false, false);
}
private Configuration configuration(Map<String, Object> configMap) {
return new Configuration(ConfigFactory.parseMap(configMap));
}
}
|
package de.muspellheim;
import javax.sql.*;
import java.sql.*;
public class JDBCFacade {
private DataSource dataSource;
public JDBCFacade(DataSource dataSource) {
this.dataSource = dataSource;
}
public void executeSQLCommand(SQLCommand command) {
try (ConnectionBuilder connection = new ConnectionBuilder(dataSource)) {
command.execute(connection);
} catch (SQLException ex) {
handleSQLException(ex);
}
}
protected void handleSQLException(SQLException ex) {
// TODO remove debug output
for (Throwable t : ex) {
String msg = "";
if (t instanceof SQLException) {
SQLException e = (SQLException) t;
msg += "SQL state: " + e.getSQLState() + ", error code: " + e.getErrorCode() + " - ";
}
msg += t;
System.err.println("ERROR: " + msg);
}
throw new UncheckedSQLException("SQL command failed: " + ex.getLocalizedMessage(), ex);
}
}
|
package ezvcard.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.Writer;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import ezvcard.VCardSubTypes;
import ezvcard.VCardVersion;
import ezvcard.parameters.EncodingParameter;
/**
* Writes data to an vCard data stream.
* @author Michael Angstadt
*/
public class VCardRawWriter implements Closeable {
/**
* Regular expression used to determine if a parameter value needs to be
* quoted.
*/
private static final Pattern quoteMeRegex = Pattern.compile(".*?[,:;].*");
/**
* Regular expression used to detect newline character sequences.
*/
private static final Pattern newlineRegex = Pattern.compile("\\r\\n|\\r|\\n");
/**
* Regular expression used to determine if a property name contains any
* invalid characters.
*/
private static final Pattern propertyNameRegex = Pattern.compile("(?i)[-a-z0-9]+");
/**
* The characters that are not valid in parameter values and that should be
* removed.
*/
private static final Map<VCardVersion, BitSet> invalidParamValueChars = new HashMap<VCardVersion, BitSet>();
static {
BitSet controlChars = new BitSet(128);
controlChars.set(0, 31);
controlChars.set(127);
controlChars.set('\t', false); //allow
controlChars.set('\n', false); //allow
controlChars.set('\r', false); //allow
{
BitSet bitSet = new BitSet(128);
bitSet.or(controlChars);
bitSet.set(',');
bitSet.set('.');
bitSet.set(':');
bitSet.set('=');
bitSet.set('[');
bitSet.set(']');
invalidParamValueChars.put(VCardVersion.V2_1, bitSet);
}
//3.0, 4.0
{
BitSet bitSet = new BitSet(128);
bitSet.or(controlChars);
invalidParamValueChars.put(VCardVersion.V3_0, bitSet);
invalidParamValueChars.put(VCardVersion.V4_0, bitSet);
}
}
private final String newline;
private boolean caretEncodingEnabled = false;
private final FoldingScheme foldingScheme;
private final FoldedLineWriter writer;
private ProblemsListener problemsListener;
private VCardVersion version;
/**
* Creates a vCard raw writer using the standard folding scheme and newline
* sequence.
* @param writer the writer to the data stream
* @param version the vCard version to adhere to
*/
public VCardRawWriter(Writer writer, VCardVersion version) {
this(writer, version, FoldingScheme.MIME_DIR);
}
/**
* Creates a vCard raw writer using the standard newline sequence.
* @param writer the writer to the data stream
* @param version the vCard version to adhere to
* @param foldingScheme the folding scheme to use or null not to fold at all
*/
public VCardRawWriter(Writer writer, VCardVersion version, FoldingScheme foldingScheme) {
this(writer, version, foldingScheme, "\r\n");
}
/**
* Creates a vCard raw writer.
* @param writer the writer to the data stream
* @param version the vCard version to adhere to
* @param foldingScheme the folding scheme to use or null not to fold at all
* @param newline the newline sequence to use
*/
public VCardRawWriter(Writer writer, VCardVersion version, FoldingScheme foldingScheme, String newline) {
if (foldingScheme == null) {
this.writer = new FoldedLineWriter(writer, -1, null, newline);
} else {
this.writer = new FoldedLineWriter(writer, foldingScheme.getLineLength(), foldingScheme.getIndent(), newline);
}
this.version = version;
this.foldingScheme = foldingScheme;
this.newline = newline;
}
public boolean isCaretEncodingEnabled() {
return caretEncodingEnabled;
}
public void setCaretEncodingEnabled(boolean enable) {
caretEncodingEnabled = enable;
}
/**
* Gets the vCard version that the writer is adhering to.
* @return the version
*/
public VCardVersion getVersion() {
return version;
}
/**
* Sets the vCard version that the writer should adhere to.
* @param version the version
*/
public void setVersion(VCardVersion version) {
this.version = version;
}
/**
* Gets the newline sequence that is used to separate lines.
* @return the newline sequence
*/
public String getNewline() {
return newline;
}
/**
* Gets the problems listener.
* @return the listener or null if not set
*/
public ProblemsListener getProblemsListener() {
return problemsListener;
}
/**
* Sets the problems listener.
* @param problemsListener the listener or null to remove
*/
public void setProblemsListener(ProblemsListener problemsListener) {
this.problemsListener = problemsListener;
}
/**
* Gets the rules for how each line is folded.
* @return the folding scheme or null if the lines are not folded
*/
public FoldingScheme getFoldingScheme() {
return foldingScheme;
}
/**
* Writes a property marking the beginning of a component (in other words,
* writes a "BEGIN:NAME" property).
* @param componentName the component name (e.g. "VCARD")
* @throws IOException if there's an I/O problem
*/
public void writeBeginComponent(String componentName) throws IOException {
writeProperty("BEGIN", componentName);
}
/**
* Writes a property marking the end of a component (in other words, writes
* a "END:NAME" property).
* @param componentName the component name (e.g. "VCARD")
* @throws IOException if there's an I/O problem
*/
public void writeEndComponent(String componentName) throws IOException {
writeProperty("END", componentName);
}
/**
* Writes a "VERSION" property, based on the vCard version that the writer
* is adhering to.
* @throws IOException if there's an I/O problem
*/
public void writeVersion() throws IOException {
writeProperty("VERSION", version.getVersion());
}
public void writeProperty(String propertyName, String value) throws IOException {
writeProperty(null, propertyName, new VCardSubTypes(), value);
}
public void writeProperty(String group, String propertyName, VCardSubTypes parameters, String value) throws IOException {
//validate the group name
if (group != null && !propertyNameRegex.matcher(group).matches()) {
throw new IllegalArgumentException("Group contains invalid characters. Valid characters are letters, numbers, and hyphens: " + group);
}
//validate the property name
if (!propertyNameRegex.matcher(propertyName).matches()) {
throw new IllegalArgumentException("Property name contains invalid characters. Valid characters are letters, numbers, and hyphens: " + propertyName);
}
value = sanitizeValue(propertyName, parameters, value);
//write the group
if (group != null) {
writer.append(group);
writer.append('.');
}
//write the property name
writer.append(propertyName);
//write the parameters
for (Map.Entry<String, List<String>> subType : parameters) {
String parameterName = subType.getKey();
List<String> parameterValues = subType.getValue();
if (parameterValues.isEmpty()) {
continue;
}
if (version == VCardVersion.V2_1) {
boolean isTypeParameter = VCardSubTypes.TYPE.equalsIgnoreCase(parameterName);
for (String parameterValue : parameterValues) {
parameterValue = sanitizeParameterValue(parameterValue, parameterName, propertyName);
if (isTypeParameter) {
//e.g. ADR;HOME;WORK:
writer.append(';').append(parameterValue.toUpperCase());
} else {
//e.g. ADR;FOO=bar;FOO=car:
writer.append(';').append(parameterName).append('=').append(parameterValue);
}
}
} else {
//e.g. ADR;TYPE=home,work,"another,value":
boolean first = true;
writer.append(';').append(parameterName).append('=');
for (String parameterValue : parameterValues) {
if (!first) {
writer.append(',');
}
parameterValue = sanitizeParameterValue(parameterValue, parameterName, propertyName);
//surround with double quotes if contains special chars
if (quoteMeRegex.matcher(parameterValue).matches()) {
writer.append('"');
writer.append(parameterValue);
writer.append('"');
} else {
writer.append(parameterValue);
}
first = false;
}
}
}
writer.append(':');
//write the property value
boolean quotedPrintable = (parameters.getEncoding() == EncodingParameter.QUOTED_PRINTABLE);
writer.append(value, quotedPrintable);
writer.append(newline);
}
/**
* Sanitizes a property value for safe inclusion in a vCard.
* @param propertyName the property name
* @param parameters the parameters
* @param value the value to sanitize
* @return the sanitized value
*/
private String sanitizeValue(String propertyName, VCardSubTypes parameters, String value) {
if (value == null) {
return "";
}
if (version == VCardVersion.V2_1 && containsNewlines(value)) {
//2.1 does not support the "\n" escape sequence (see "Delimiters" sub-section in section 2 of the specs)
parameters.setEncoding(EncodingParameter.QUOTED_PRINTABLE);
return value;
}
return escapeNewlines(value);
}
/**
* Removes or escapes all invalid characters in a parameter value.
* @param parameterValue the parameter value
* @param parameterName the parameter name
* @param propertyName the name of the property to which the parameter
* belongs
* @return the sanitized parameter value
*/
private String sanitizeParameterValue(String parameterValue, String parameterName, String propertyName) {
String modifiedValue = null;
boolean valueChanged = false;
//Note: String reference comparisons ("==") are used because the Pattern class returns the same instance if the String wasn't changed
switch (version) {
case V2_1:
//remove invalid characters
modifiedValue = removeInvalidParameterValueChars(parameterValue);
//replace newlines with spaces
modifiedValue = newlineRegex.matcher(modifiedValue).replaceAll(" ");
//check to see if value was changed
valueChanged = (parameterValue != modifiedValue);
//escape backslashes
modifiedValue = modifiedValue.replace("\\", "\\\\");
//escape semi-colons (see section 2)
modifiedValue = modifiedValue.replace(";", "\\;");
break;
case V3_0:
//remove invalid characters
modifiedValue = removeInvalidParameterValueChars(parameterValue);
if (caretEncodingEnabled) {
valueChanged = (modifiedValue != parameterValue);
//apply caret encoding
modifiedValue = applyCaretEncoding(modifiedValue);
} else {
//replace double quotes with single quotes
modifiedValue = modifiedValue.replace('"', '\'');
//replace newlines with spaces
modifiedValue = newlineRegex.matcher(modifiedValue).replaceAll(" ");
valueChanged = (modifiedValue != parameterValue);
}
break;
case V4_0:
//remove invalid characters
modifiedValue = removeInvalidParameterValueChars(parameterValue);
if (caretEncodingEnabled) {
valueChanged = (modifiedValue != parameterValue);
//apply caret encoding
modifiedValue = applyCaretEncoding(modifiedValue);
} else {
//replace double quotes with single quotes
modifiedValue = modifiedValue.replace('"', '\'');
valueChanged = (modifiedValue != parameterValue);
//backslash-escape newlines (for the "LABEL" parameter)
modifiedValue = newlineRegex.matcher(modifiedValue).replaceAll("\\\\\\n");
}
break;
}
if (valueChanged && problemsListener != null) {
problemsListener.onParameterValueChanged(propertyName, parameterName, parameterValue, modifiedValue);
}
return modifiedValue;
}
/**
* Removes invalid characters from a parameter value.
* @param value the parameter value
* @return the sanitized parameter value
*/
private String removeInvalidParameterValueChars(String value) {
BitSet invalidChars = invalidParamValueChars.get(version);
StringBuilder sb = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (!invalidChars.get(ch)) {
sb.append(ch);
}
}
return (sb.length() == value.length()) ? value : sb.toString();
}
/**
* Applies circumflex accent encoding to a string.
* @param value the string
* @return the encoded string
*/
private String applyCaretEncoding(String value) {
value = value.replace("^", "^^");
value = newlineRegex.matcher(value).replaceAll("^n");
value = value.replace("\"", "^'");
return value;
}
/**
* <p>
* Escapes all newline character sequences. The newline character sequences
* are:
* </p>
* <ul>
* <li>{@code \r\n}</li>
* <li>{@code \r}</li>
* <li>{@code \n}</li>
* </ul>
* @param text the text to escape
* @return the escaped text
*/
private String escapeNewlines(String text) {
return newlineRegex.matcher(text).replaceAll("\\\\n");
}
/**
* <p>
* Determines if a string has at least one newline character sequence. The
* newline character sequences are:
* </p>
* <ul>
* <li>{@code \r\n}</li>
* <li>{@code \r}</li>
* <li>{@code \n}</li>
* </ul>
* @param text the text to escape
* @return the escaped text
*/
private boolean containsNewlines(String text) {
return newlineRegex.matcher(text).find();
}
/**
* Closes the underlying {@link Writer} object.
*/
public void close() throws IOException {
writer.close();
}
/**
* A listener whose methods are invoked when non-critical issues occur
* during the writing process.
* @author Michael Angstadt
*/
public static interface ProblemsListener {
/**
* Called when a parameter value is changed in a lossy way, due to it
* containing invalid characters. If a character can be escaped (such as
* the "^" character when caret encoding is enabled), then this does not
* count as the parameter being modified because it can be decoded
* without losing any information.
* @param propertyName the name of the property to which the parameter
* belongs
* @param parameterName the parameter name
* @param originalValue the original parameter value
* @param modifiedValue the modified parameter value
*/
void onParameterValueChanged(String propertyName, String parameterName, String originalValue, String modifiedValue);
}
}
|
package br.com.redesocial.modelo.bo;
import br.com.redesocial.modelo.dto.Album;
import br.com.redesocial.modelo.dto.Cidade;
import br.com.redesocial.modelo.dto.Estado;
import br.com.redesocial.modelo.dto.Pais;
import br.com.redesocial.modelo.dto.Usuario;
import br.com.redesocial.modelo.dto.enumeracoes.Sexo;
import br.com.redesocial.modelo.utilitarios.Utilitarios;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unidade de testes para o AlbumBO
* @author Ronneesley Moura Teles, Ianka Talita Bastos de Assis
* @since 16/08/2017
*/
public class AlbumBOTest {
@Test
public void testMetodoInserir() {
Pais pais = new Pais();
pais.setNome("EUA");
try {
PaisBO paisBO = new PaisBO();
paisBO.inserir(pais);
Estado estado = new Estado();
estado.setNome("California");
estado.setPais(pais);
EstadoBO estadoBO = new EstadoBO();
estadoBO.inserir(estado);
Cidade cidade = new Cidade();
cidade.setNome("Los Angeles");
cidade.setEstado(estado);
CidadeBO cidadeBO = new CidadeBO();
cidadeBO.inserir(cidade);
Usuario usuario = new Usuario();
usuario.setNome("Paul");
usuario.setDataCadastro(new Date());
usuario.setEmail("paul@gmail.com");
//usuario.setFoto();
Calendar calendario = Calendar.getInstance();
calendario.set(1988, 2, 7, 0, 0, 0);
usuario.setDataNascimento(calendario.getTime());
usuario.setSenha("123");
usuario.setSexo(Sexo.MASCULINO);
usuario.setStatus(true);
usuario.setTelefone("(62) 91234-4567");
usuario.setCidade(cidade);
UsuarioBO usuarioBO = new UsuarioBO();
usuarioBO.inserir(usuario);
AlbumBO bo = new AlbumBO();
Album album = new Album();
album.setNome("Hollywood");
calendario.set(2016, 8, 29, 0, 0, 0);
album.setData(calendario.getTime());
album.setUsuario(usuario);
/**
* Os dados do album foram definidos para inserir no banco de dados
*/
bo.inserir(album);
} catch (Exception ex) {
fail("Falha ao inserir um album: " + ex.getMessage());
}
}
@Test
public void testMetodoListar() {
AlbumBO bo = new AlbumBO();
try {
/**
* Verifica a quantidade de albuns existentes no banco de dados
*/
List existentes = bo.listar();
int qtdeExistentes = existentes.size();
/**
* Define a quantidade a ser listada
*/
final int qtde = 10;
for (int i = 0; i < 10; i++){
Pais pais = new Pais();
pais.setNome("EUA");
PaisBO paisBO = new PaisBO();
paisBO.inserir(pais);
Estado estado = new Estado();
estado.setNome("California");
estado.setPais(pais);
EstadoBO estadoBO = new EstadoBO();
estadoBO.inserir(estado);
Cidade cidade = new Cidade();
cidade.setNome("Los Angeles");
cidade.setEstado(estado);
CidadeBO cidadeBO = new CidadeBO();
cidadeBO.inserir(cidade);
Usuario usuario = new Usuario();
usuario.setNome("Paul");
usuario.setDataCadastro(new Date());
usuario.setEmail("paul@gmail.com");
Calendar calendario = Calendar.getInstance();
calendario.set(1988, 2, 7, 0, 0, 0);
usuario.setDataNascimento(calendario.getTime());
usuario.setSenha("123");
usuario.setSexo(Sexo.MASCULINO);
usuario.setStatus(true);
usuario.setTelefone("(62) 91234-4567");
usuario.setCidade(cidade);
UsuarioBO usuarioBO = new UsuarioBO();
usuarioBO.inserir(usuario);
Album album = new Album();
album.setNome("Hollywood");
album.setData(new Date());
album.setUsuario(usuario);
/**
* Os dados do album foram definidos para inserir no banco de dados
*/
try {
bo.inserir(album);
} catch (Exception ex) {
fail("Falha ao inserir um álbum: " + ex.getMessage());
}
}
List existentesFinal = bo.listar();
int qtdeExistentesFinal = existentesFinal.size();
/**
* Verifica a quantidade de albuns realmente inseridos
*/
int diferenca = qtdeExistentesFinal - qtdeExistentes;
/**
* Compara a quantidade definida para listagem e a quantidade de
* albuns inseridos, finaliza se estiver tudo certo
*/
assertEquals(qtde, diferenca);
} catch (Exception ex){
fail("Erro ao listar: " + ex.getMessage());
}
}
@Test
public void testMetodoSelecionar() {
Pais pais = new Pais();
pais.setNome("Brasil");
try {
PaisBO paisBO = new PaisBO();
paisBO.inserir(pais);
Estado estado = new Estado();
estado.setNome("Goiás");
estado.setPais(pais);
EstadoBO estadoBO = new EstadoBO();
estadoBO.inserir(estado);
Cidade cidade = new Cidade();
cidade.setNome("Ceres");
cidade.setEstado(estado);
CidadeBO cidadeBO = new CidadeBO();
cidadeBO.inserir(cidade);
Usuario usuario = new Usuario();
usuario.setNome("Igor");
usuario.setDataCadastro(new Date());
usuario.setEmail("igor@gmail.com");
//usuario.setFoto();
Calendar calendario = Calendar.getInstance();
calendario.set(1988, 2, 7, 0, 0, 0);
usuario.setDataNascimento(calendario.getTime());
usuario.setSenha("123");
usuario.setSexo(Sexo.MASCULINO);
usuario.setStatus(true);
usuario.setTelefone("(62) 99654-0873");
usuario.setCidade(cidade);
UsuarioBO usuarioBO = new UsuarioBO();
usuarioBO.inserir(usuario);
Album album = new Album();
album.setNome("Album1");
calendario.set(1998, 0, 8, 0, 0, 0);
album.setData(calendario.getTime());
album.setUsuario(usuario);
AlbumBO albumbo = new AlbumBO();
albumbo.inserir(album);
int idalbum = album.getId();
albumbo.selecionar(idalbum);
} catch (Exception ex) {
fail("Falha ao inserir um comentário: " + ex.getMessage());
}
}
@Test
public void testMetodoExcluir () throws Exception {
AlbumBO albumBO = new AlbumBO();
try{ // tenta inserir e em seguida seleciona
PaisBO paisBO = new PaisBO();
Pais pais = new Pais();
pais.setNome("Brasil");
paisBO.inserir(pais);
EstadoBO estadoBO = new EstadoBO();
Estado estado = new Estado();
estado.setNome("Goiás");
estado.setPais(pais);
estadoBO.inserir(estado);
CidadeBO cidadeBO = new CidadeBO();
Cidade cidade = new Cidade();
cidade.setNome("Bragolândia");
cidade.setEstado(estado);
cidadeBO.inserir(cidade);
UsuarioBO usuarioBO = new UsuarioBO();
Usuario usuario = new Usuario();
usuario.setNome("Ianka");
usuario.setDataCadastro(new Date());
usuario.setEmail("iankatalitaa@gmail.com");
//usuario.setFoto();
Calendar calendario = Calendar.getInstance();
calendario.set(1997, 1, 15, 0, 0, 0);
usuario.setDataNascimento(calendario.getTime());
usuario.setSenha("gaivotinha");
usuario.setSexo(Sexo.FEMININO);
usuario.setStatus(true);
usuario.setTelefone("(62) 98483-0937");
usuario.setCidade(cidade);
usuarioBO.inserir(usuario);
calendario.set(2016, 8, 28, 0, 0, 0);
Album album = new Album ();
album.setNome("Desisto, Ronne!");
album.setData(calendario.getTime());
album.setUsuario(usuario);
albumBO.inserir(album);
int id = album.getId();
Album albumSelecionado = albumBO.selecionar(id);
assertNotNull("Album não encontrado", albumSelecionado);
albumBO.excluir(id);
Album albumSelecionadoPosExclusao = albumBO.selecionar(id);
assertNull("Album não encontrado", albumSelecionadoPosExclusao);
} catch (Exception ex){
fail("Falha ao inserir um album: " + ex.getMessage());
}
}
}
|
package genepi.bam;
import genepi.util.Chromosome;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.reference.FastaSequenceFile;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeBuilder;
import htsjdk.variant.variantcontext.GenotypesContext;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import htsjdk.variant.vcf.VCFConstants;
import htsjdk.variant.vcf.VCFFormatHeaderLine;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import htsjdk.variant.vcf.VCFHeaderLineType;
import htsjdk.variant.vcf.VCFHeaderVersion;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.apache.commons.math3.stat.interval.AgrestiCoullInterval;
import org.apache.commons.math3.stat.interval.ClopperPearsonInterval;
import org.apache.commons.math3.stat.interval.ConfidenceInterval;
import org.apache.commons.math3.stat.interval.WilsonScoreInterval;
public class VariantBuilder {
private String genome;
private String reference;
private String excludeList;
private String outDirectory;
private double vaf;
private int qual;
private int mapqual;
private boolean checkRCRS;
public VariantBuilder(String genome) {
this.genome = genome;
}
public <BaqAlt> int build() throws MalformedURLException, IOException {
//int qualPhred = 30; // default
String prev = "";
checkRCRS = false;
// create final output directory
createFolder(outDirectory);
final SamReader reader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT)
.open(new File(genome));
final SAMSequenceDictionary dict = reader.getFileHeader().getSequenceDictionary();
String SampleName = new File(genome).getName();
File refFasta = new File(reference);
FastaSequenceFile ref = new FastaSequenceFile(refFasta, true); // boolean
// for
// truncating
// Names
// whitespaces
ReferenceSequence reference = ref.nextSequence();
int size = getReferenceLength(dict, reference.length());
String name = SampleName;
System.out.println("NAME " + name);
int total = 0;
int readFWD = 0;
int readREV = 0;
int countAf = 0;
int countCf = 0;
int countGf = 0;
int countTf = 0;
int countNf = 0;
int countDf = 0;
int countAr = 0;
int countCr = 0;
int countGr = 0;
int countTr = 0;
int countNr = 0;
int countDr = 0;
int countIAf = 0;
int countICf = 0;
int countIGf = 0;
int countITf = 0;
int countIAr = 0;
int countICr = 0;
int countIGr = 0;
int countITr = 0;
HashMap<Integer, HashMap<String, Integer>> hm = new HashMap<>();
Locale.setDefault(new Locale("en", "US"));
NumberFormat formatter = new DecimalFormat("#0.0000");
// quality threshold per base
double het = vaf; // heteroplasmy threshold to be applied (1=100%, 0.5 =
int row = size;
int columns = 20; // 4 base forward (A,C,G,T), N, D, I*4 + all of it reverse
int basePos =0;
int[][] result = new int[row][columns];
for (int i = 0; i < row; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = 0;
}
}
try {
for (SAMRecord samRecord : reader) {
// Convert read name to upper case.
if (samRecord.getMappingQuality() > qual) {
if (!samRecord.getReadUnmappedFlag()) {
// if (!samRecord.getDuplicateReadFlag())
{
if (samRecord.getReadLength() > 25) {
//Alignmentscore AS between 0 and 255 (perfect)
if (!samRecord.getNotPrimaryAlignmentFlag()){
String help = (samRecord.getAttribute("AS") + "");
if (help.equals("null") || Integer.valueOf(help) >= mapqual){
String read = samRecord.getReadString();
for (int j = 0; j < read.length(); j++) {
byte[] quality = samRecord.getBaseQualities();
if (quality.length==0 || quality[j] >= qual) {
int posBase = samRecord.getReferencePositionAtReadPosition(j + 1);
if ((samRecord.getFlags() & 0x10) == 0x10) {
if (checkRCRS) // if HG19 Yoruba
posBase = checkRCRS(posBase);
switch (read.charAt(j)) {
case 'A':
result[posBase % (size)][0]++;
countAf++;
break;
case 'C':
result[posBase % (size)][1]++;
countCf++;
break;
case 'G':
result[posBase % (size)][2]++;
countGf++;
break;
case 'T':
result[posBase % (size)][3]++;
countTf++;
break;
case 'N':
result[posBase % (size)][4]++;
countNf++;
break;
case 'D':
result[posBase % (size)][5]++;
countDf++;
break;
default:
break;
}
} else {
if (quality.length==0 || quality[j] >= qual) {
if (checkRCRS) // if HG19
// Yoruba
// //(reference.length()
// ==16571)
posBase = checkRCRS(posBase);
switch (read.charAt(j)) {
case 'A':
result[posBase % (size)][6]++;
countAr++;
break;
case 'C':
result[posBase % (size)][7]++;
countCr++;
break;
case 'G':
result[posBase % (size)][8]++;
countGr++;
break;
case 'T':
result[posBase % (size)][9]++;
countTr++;
break;
case 'N':
result[posBase % (size)][10]++;
countNr++;
break;
case 'D':
result[posBase % (size)][11]++;
countDr++;
break;
default:
break;
}
}
}
}
}
}
total++;
if ((samRecord.getFlags() & 0x10) == 16) // check forward
// or reverse
readREV++;
else
readFWD++;
Integer currentReferencePos = samRecord.getAlignmentStart();
int posCigar=0;
for (CigarElement cigarElement : samRecord.getCigar().getCigarElements()) {
if (cigarElement.getOperator() != CigarOperator.S){
posCigar+= cigarElement.getLength();
}
if (cigarElement.getOperator() == CigarOperator.D) {
posCigar-= cigarElement.getLength();
Integer cigarElementStart = currentReferencePos;
Integer cigarElementLength = cigarElement.getLength();
Integer cigarElementEnd = currentReferencePos + cigarElementLength;
while (cigarElementStart < cigarElementEnd) {
if ((samRecord.getFlags() & 0x10) == 0x10) {
countDf++;
result[(cigarElementEnd - cigarElementLength) % (size - 1)][11]++;
} else {
countDr++;
result[(cigarElementStart - cigarElementLength + 1) % (size - 1)][5]++;
}
cigarElementStart += cigarElementLength;
}
} else
currentReferencePos += cigarElement.getLength();
/*
* TODO check insertions
*/
if (cigarElement.getOperator() ==
CigarOperator.I) {
Integer cigarElementLength = cigarElement.getLength();
int i = 0;
while (i <= cigarElementLength) {
char insBase = samRecord.getReadString().charAt(posCigar-1+i);
if ((samRecord.getFlags() & 0x10) == 0x10) {
//REVERSE
switch (insBase) {
case 'A':
result[currentReferencePos +i % (size)][16]++;
countIAr++;
break;
case 'C':
result[currentReferencePos +i % (size)][17]++;
countICr++;
break;
case 'G':
result[currentReferencePos +i % (size)][18]++;
countIGr++;
break;
case 'T':
result[currentReferencePos +i % (size)][19]++;
countITr++;
break;
default:
break;
}
}
else {
//FORWARD
switch (insBase) {
case 'A':
result[currentReferencePos +i % (size)][12]++;
countIAf++;
break;
case 'C':
result[currentReferencePos +i % (size)][13]++;
countICf++;
break;
case 'G':
result[currentReferencePos +i % (size)][14]++;
countIGf++;
break;
case 'T':
result[currentReferencePos +i % (size)][15]++;
countITf++;
break;
default:
break;
}
}
i++;
}
}
}
}
}
}
}
}
}
} catch (Exception e) {
System.out.println("Error with BAM file");
e.printStackTrace();
}
writePileup(outDirectory + File.separator + name + ".pileup", size, columns, result);
System.out.println(outDirectory + File.separator + name);
System.out.println("All Reads " + total + "\nStrand\t A\tC\tG\tT\tN\tD\tInsA\tInsC\tInsG\tInsT\n" +
"Forward\t" + countAf + "\t" + countCf + "\t" + countGf + "\t" + countTf + "\t" + countNf + "\t" + countDf + "\t" + countIAf + "\t" + countICf + "\t" + countIGf + "\t" + countITf+ "\n" +
"Reverse\t" + countAr + "\t" + countCr + "\t" + countGr + "\t" + countTr + "\t" + countNr + "\t" + countDr + "\t" + countIAr + "\t" + countICr + "\t" + countIGr + "\t" + countITr + "\t" + "\n");
//Internal Data Structure
TreeMap<Integer, String> variants = new TreeMap<>();
TreeMap<Integer, String> indels = new TreeMap<>();
for (int i = 1; i < size; i++) {
int pos = i;
TreeMap<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());
if (checkRCRS){
if (pos >= 315 && pos <= 3107)
pos = pos - 2;
else if (pos > 3107 && pos <= 16192)
pos = pos - 1;
else if (pos > 16192)
pos = pos - 2;
}
map.put(result[pos][0] + result[pos][6], "A");
map.put(result[pos][1] + result[pos][7], "C");
map.put(result[pos][2] + result[pos][8], "G");
map.put(result[pos][3] + result[pos][9], "T");
double major = 0;
// System.out.print("\n"+i+" "+ref.charAt(i-1)+" ");
for (Entry<Integer, String> entry : map.entrySet()) {
if (entry.getKey() > 0) {
if (variants.containsKey(pos)) {
variants.put(pos, variants.get(pos) + "\t" + entry.getKey() + "\t" + entry.getValue() + "\t"
+ formatter.format((entry.getKey() / (entry.getKey() + major))));
} else {
variants.put(pos, reference.getBaseString().charAt(pos - 1) + "\t" + entry.getKey() + "\t"
+ entry.getValue());
major = entry.getKey();
}
}
}
}
writeVariants(outDirectory + File.separator + name + ".txt", name, formatter, het, variants);
System.out.println(prev + " - input BAM file: " + genome);
System.out.println(prev + " - reference size: " + reference.length());
System.out.println(" Results saved in: " + outDirectory);
ref.close();
return 0;
}
private void writeVariants(String filename, String name, NumberFormat formatter, double het,
TreeMap<Integer, String> variants) throws IOException {
File fout = new File(filename);
FileOutputStream fstream = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fstream));
File fout1 = new File(filename + ".hsd");
FileOutputStream fstream1 = new FileOutputStream(fout1);
BufferedWriter bwHsd = new BufferedWriter(new OutputStreamWriter(fstream1));
bwHsd.write(name + "\t1-16569\t\t");
bw.write(
"SampleID\tmtSNP\tPOS\tREFrCRS\tcountMajor\tBaseMajor\tcountMinor\tBaseMinor\tVAF\tClopperPearson_95_low\tClopperPearson_95_high\n");
for (Entry<Integer, String> entry : variants.entrySet()) {
String help = entry.getValue();
StringTokenizer st = new StringTokenizer(help);
String Ref = st.nextToken();
Ref = Ref.toUpperCase();
int countMajor = Integer.valueOf(st.nextToken());
String Max = st.nextToken();
// System.out.println(" " + entry.getValue() +" "+ entry.getKey());
if (st.hasMoreTokens()) {
int numberMin = Integer.valueOf(st.nextToken()); // numberMin
String ALT = st.nextToken(); // VariantMin
double hetlevel = Double.valueOf(st.nextToken());
if (hetlevel >= het) {
int n = countMajor + numberMin;
double p = (double) (numberMin / (double) (n));
if (Ref.equals(Max)) {
bw.write(name + "\t" + entry.getKey() + Max + "\t" + entry.getKey() + "\t" + Ref + "\t"
+ countMajor + "\t" + Max + "\t" + numberMin + "\t" + ALT + "\t" + hetlevel + "\t"
+ formatter.format(getClopperPearsonInterval(n, numberMin, 0.95).getLowerBound()) + "\t"
+ formatter.format(getClopperPearsonInterval(n, numberMin, 0.95).getUpperBound())
+ "\n");
} else if (!Ref.equals("N")) {
bw.write(name + "\t" + entry.getKey() + Max + "\t" + entry.getKey() + "\t" + Ref + "\t"
+ countMajor + "\t" + Max + "\t" + numberMin + "\t" + ALT + "\t"
+ formatter.format(1 - hetlevel) + "\t"
+ formatter.format(getClopperPearsonInterval(n, numberMin, 0.95).getLowerBound()) + "\t"
+ formatter.format(getClopperPearsonInterval(n, numberMin, 0.95).getUpperBound())
+ "\n");
bwHsd.write(entry.getKey() + Max + "\t");
}
} else {
if (!Ref.equals(Max) && hetlevel < 1 - het) {
bw.write(name + "\t" + entry.getKey() + Max + "\t" + entry.getKey() + "\t" + Ref + "\t"
+ countMajor + "\t" + Max + "\t" + numberMin + "\t" + ALT + "\t"
+ formatter.format(1 - hetlevel) + "\n");
bwHsd.write(entry.getKey() + Max + "\t");
}
}
} else {
if (!Ref.equals(Max)) {
bw.write(name + "\t" + entry.getKey() + Max + "\t" + entry.getKey() + "\t" + Ref + "\t" + countMajor
+ "\t" + Max + "\t" + "\t" + "\t1\n");
bwHsd.write(entry.getKey() + Max + "\t");
}
}
}
bw.close();
bwHsd.close();
fstream.close();
fstream1.close();
}
private double binConfInterval(int n, double p, int low) {
return p + (1.96 * low) * Math.sqrt((p * (1 - p)) / n);
}
private ConfidenceInterval getWilsonScoreInterval(int coverage, int variants, double confidencelevel) {
WilsonScoreInterval wi = new WilsonScoreInterval();
ConfidenceInterval ci = wi.createInterval(coverage, variants, confidencelevel);
return ci;
}
private ConfidenceInterval getAgrestiCoullInterval(int coverage, int variants, double confidencelevel) {
AgrestiCoullInterval aci = new AgrestiCoullInterval();
ConfidenceInterval ci = aci.createInterval(coverage, variants, confidencelevel);
return ci;
}
private ConfidenceInterval getClopperPearsonInterval(int coverage, int variants, double confidencelevel) {
ClopperPearsonInterval cpi = new ClopperPearsonInterval();
ConfidenceInterval ci = cpi.createInterval(coverage, variants, confidencelevel);
return ci;
}
private void writePileup(String filename, int size, int columns, int[][] result) throws IOException {
File fout = new File(filename);
FileOutputStream fstream = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fstream));
bw.write("POS\tA\tC\tG\tT\tN\tDEL\ta\tc\tg\tt\tn\tdel\t.A\t.C\t.G\t.T\t.a\t.c\t.g\t.t\n");
for (int i = 0; i < size; i++) {
bw.write((i) + "\t");
for (int j = 0; j < columns; j++) {
bw.write(result[i][j] + "\t");
}
bw.newLine();
}
bw.close();
fstream.close();
}
private VCFHeader generateHeader(String name, String chromosome) {
Set<VCFHeaderLine> headerLines = new HashSet<VCFHeaderLine>();
Set<String> additionalColumns = new HashSet<String>();
headerLines.add(new VCFHeaderLine(VCFHeaderVersion.VCF4_0.getFormatString(),
VCFHeaderVersion.VCF4_0.getVersionString()));
headerLines.add(new VCFFormatHeaderLine(VCFConstants.GENOTYPE_KEY, 1, VCFHeaderLineType.String, "Genotype"));
additionalColumns.add(name);
SAMSequenceDictionary sequenceDict = generateSequenceDictionary(chromosome);
VCFHeader header = new VCFHeader(headerLines, additionalColumns);
header.setSequenceDictionary(sequenceDict);
return header;
}
private SAMSequenceDictionary generateSequenceDictionary(String chromosome) {
SAMSequenceDictionary sequenceDict = new SAMSequenceDictionary();
SAMSequenceRecord newSequence = new SAMSequenceRecord(chromosome, Chromosome.getChrLength(chromosome));
sequenceDict.addSequence(newSequence);
return sequenceDict;
}
private VariantContext createVC(VCFHeader header, String chrom, String rsid, List<Allele> alleles,
List<Allele> genotype, int position) {
final Map<String, Object> attributes = new HashMap<String, Object>();
final GenotypesContext genotypes = GenotypesContext.create(header.getGenotypeSamples().size());
for (final String name : header.getGenotypeSamples()) {
final Genotype gt = new GenotypeBuilder(name, genotype).phased(false).make();
genotypes.add(gt);
}
return new VariantContextBuilder("23andMe", chrom, position, position, alleles).genotypes(genotypes)
.attributes(attributes).id(rsid).make();
}
public int getReferenceLength(SAMSequenceDictionary dict, int referencesize) {
int size = 0;
for (SAMSequenceRecord rc : dict.getSequences()) {
if (rc.getSequenceLength() == referencesize) {
size = referencesize + 1;
break;
}
}
return size;
}
private static int checkRCRS(int pos) {
if (pos >= 315 && pos <= 3107)
pos = pos - 2;
else if (pos > 3107 && pos <= 16192)
pos = pos - 1;
else if (pos > 16192)
pos = pos - 2;
return pos;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getExcludeList() {
return excludeList;
}
public void setExcludeList(String excludeList) {
this.excludeList = excludeList;
}
public String getOutDirectory() {
return outDirectory;
}
public void setOutDirectory(String outDirectory) {
this.outDirectory = outDirectory;
}
private double getVaf() {
return vaf;
}
public void setVaf(double vaf) {
this.vaf = vaf;
}
private int getQual() {
return qual;
}
public void setQual(int qual) {
this.qual = qual;
}
public int getMapqual() {
return mapqual;
}
public void setMapqual(int mapqual) {
this.mapqual = mapqual;
}
public boolean createFolder(String directoryName) {
File directory = new File(directoryName);
boolean result = false;
// if the directory does not exist, create it
if (!directory.exists()) {
System.out.println("creating directory: " + directoryName);
result = false;
try {
directory.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
return result;
}
}
|
package handler;
import misc.Logger;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.*;
import java.util.List;
import java.util.Scanner;
public class StatisticsHandler {
/** The number of bytes encoded, per second, across all recorded encode Jobs. */
private long bytesEncodedPerSecond;
/** The number of bytes decoded, per second, across all recorded decode Jobs. */
private long bytesDecodedPerSecond;
/**
* Constructs a new StatisticsHandler and processes all of the
* existing statistics records.
*/
public StatisticsHandler() {
processStatistcsFiles();
}
/**
* Reads in all existing en/decode data from the respective
* statistics files, averages the data, then sets the bytes
* en/decoded per second variables.
*/
private void processStatistcsFiles() {
final File file_encode = new File("statistics_encode.txt");
final File file_dedode = new File("statistics_decode.txt");
long bytesEncodedPerSecondTotal = 0;
long bytesDecodedPerSecondTotal = 0;
long totalEncodeRecords = 0;
long totalDecodeRecords = 0;
// Load the total amount of bytes encoded per second from all
// records of the statistics_encode.txt file.
if(file_encode.exists()) {
try {
final Scanner sc = new Scanner(new FileInputStream(file_encode));
while(sc.hasNextLong()) {
bytesEncodedPerSecondTotal += sc.nextLong();
totalEncodeRecords++;
}
} catch(final FileNotFoundException e) {
Logger.writeLog("Could not locate the statistics_encode.txt file", Logger.LOG_TYPE_VERBOSE);
}
}
// Load the total amount of bytes decoded per second from all
// records of the statistics_decode.txt file.
if(file_dedode.exists()) {
try {
final Scanner sc = new Scanner(new FileInputStream(file_dedode));
while(sc.hasNextLong()) {
bytesDecodedPerSecondTotal += sc.nextLong();
totalDecodeRecords++;
}
} catch(final FileNotFoundException e) {
Logger.writeLog("Could not locate the statistics_decode.txt file", Logger.LOG_TYPE_VERBOSE);
}
}
// Calculate the average bytes en/decoded per second
// from all acquired data.
if(totalEncodeRecords > 0) {
bytesEncodedPerSecond = (bytesEncodedPerSecondTotal / totalEncodeRecords);
}
if(totalDecodeRecords > 0 ) {
bytesDecodedPerSecond = (bytesDecodedPerSecondTotal / totalDecodeRecords);
}
}
/**
* Calculates the amount of bytes, per second, that the specified file was processed
* at.
* @param file The file that was processed.
* @param startTime The time, in milliseconds, that processing began.
* @param endTime The time, in milliseconds, that processing completed.
* @return The amount of bytes, per second, that the specified file was processed at.
*/
public long calculateProcessingSpeed(final File file, final long startTime, final long endTime) {
long duration = endTime - startTime; // The total time that the Job ran for, in milliseconds.
duration /= 1000; // The total time that the Job ran for, in seconds.
long speed = file.length() / duration; // The bytes per millisecond that were en/decoded.
return speed;
}
/**
* Writes the specified data to either the encode, or decode, statistics
* file.
* @param isEncodeJob Whether or not the data is from an encode or decode Job.
* @param bytesPerSecond The bytes per second to write to the file.
*/
public void recordData(final boolean isEncodeJob, final long bytesPerSecond) {
// Prepare the output file:
final File outputFile;
if(isEncodeJob) {
outputFile = new File("statistics_encode.txt");
} else {
outputFile = new File("statistics_decode.txt");
}
// Create the file if it does not exist.
if(!outputFile.exists()) {
try {
outputFile.createNewFile();
} catch(final IOException e) {
Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_ERROR);
}
}
// Append data to the output file.
try {
final PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, true)));
printWriter.append(bytesPerSecond + System.lineSeparator());
printWriter.close();
} catch(final IOException e) {
Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_ERROR);
}
}
/**
* Estimates the time it will take for a Job, with the specified files, to
* either encode, or decode, based on previous data.
* @param isEncodeJob Whether of not the Job to be run is an encode, or decode, Job.
* @param files The files to be processed.
* @return The amount of time, in seconds, that the Job may take.
*/
public long estimateProcessingDuration(final boolean isEncodeJob, final List<File> files) {
long estimation = 0;
for(final File f : files) {
estimation += f.length();
}
estimation /= (isEncodeJob ? bytesEncodedPerSecond : bytesDecodedPerSecond);
return estimation;
}
////////////////////////////////////////////////////////// Getters
/** @return The number of bytes encoded, per second, across all recorded encode Jobs. */
public long getBytesEncodedPerSecond() {
return bytesEncodedPerSecond;
}
/** @return The number of bytes decoded, per second, across all recorded decode Jobs. */
public long getBytesDecodedPerSecond() {
return bytesDecodedPerSecond;
}
}
|
package istc.bigdawg.rest;
import istc.bigdawg.exceptions.BigDawgCatalogException;
import istc.bigdawg.exceptions.QueryParsingException;
import weka.associations.tertius.Head;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;
public final class URLUtil {
private final static String UserAgent = "bigdawg/1";
private final static String[] percentTable = {
"%00",
"%01",
"%02",
"%03",
"%04",
"%05",
"%06",
"%07",
"%08",
"%09",
"%0A",
"%0B",
"%0C",
"%0D",
"%0E",
"%0F",
"%10",
"%11",
"%12",
"%13",
"%14",
"%15",
"%16",
"%17",
"%18",
"%19",
"%1A",
"%1B",
"%1C",
"%1D",
"%1E",
"%1F",
"%20",
"%21",
"%22",
"%23",
"%24",
"%25",
"%26",
"%27",
"%28",
"%29",
"%2A",
"%2B",
"%2C",
"-",
".",
"%2F",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"%3A",
"%3B",
"%3C",
"%3D",
"%3E",
"%3F",
"%40",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"%5B",
"%5C",
"%5D",
"%5E",
"_",
"%60",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"%7B",
"%7C",
"%7D",
"~",
"%7F",
"%80",
"%81",
"%82",
"%83",
"%84",
"%85",
"%86",
"%87",
"%88",
"%89",
"%8A",
"%8B",
"%8C",
"%8D",
"%8E",
"%8F",
"%90",
"%91",
"%92",
"%93",
"%94",
"%95",
"%96",
"%97",
"%98",
"%99",
"%9A",
"%9B",
"%9C",
"%9D",
"%9E",
"%9F",
"%A0",
"%A1",
"%A2",
"%A3",
"%A4",
"%A5",
"%A6",
"%A7",
"%A8",
"%A9",
"%AA",
"%AB",
"%AC",
"%AD",
"%AE",
"%AF",
"%B0",
"%B1",
"%B2",
"%B3",
"%B4",
"%B5",
"%B6",
"%B7",
"%B8",
"%B9",
"%BA",
"%BB",
"%BC",
"%BD",
"%BE",
"%BF",
"%C0",
"%C1",
"%C2",
"%C3",
"%C4",
"%C5",
"%C6",
"%C7",
"%C8",
"%C9",
"%CA",
"%CB",
"%CC",
"%CD",
"%CE",
"%CF",
"%D0",
"%D1",
"%D2",
"%D3",
"%D4",
"%D5",
"%D6",
"%D7",
"%D8",
"%D9",
"%DA",
"%DB",
"%DC",
"%DD",
"%DE",
"%DF",
"%E0",
"%E1",
"%E2",
"%E3",
"%E4",
"%E5",
"%E6",
"%E7",
"%E8",
"%E9",
"%EA",
"%EB",
"%EC",
"%ED",
"%EE",
"%EF",
"%F0",
"%F1",
"%F2",
"%F3",
"%F4",
"%F5",
"%F6",
"%F7",
"%F8",
"%F9",
"%FA",
"%FB",
"%FC",
"%FD",
"%FE",
"%FF"
};
static String percentEncode(String str) {
StringBuilder sb = new StringBuilder();
for (int $i = 0, len = str.length(); $i < len; $i++) {
sb.append(URLUtil.percentTable[(int)str.charAt($i)]);
}
return sb.toString();
}
public static class FetchResult {
public String response;
public int responseCode;
public Map<String, List<String>> responseHeaders;
}
static FetchResult fetch(String urlStr, HttpMethod method, Map<String, String> headers, String postData, int connectTimeout, int readTimeout) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(connectTimeout);
urlConnection.setReadTimeout(readTimeout);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod(method.name());
urlConnection.setRequestProperty("User-Agent", UserAgent);
for(String header: headers.keySet()) {
urlConnection.setRequestProperty(header, headers.get(header));
}
urlConnection.setDoInput(true);
if (postData != null && method == HttpMethod.POST) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
OutputStream os = urlConnection.getOutputStream();
DataOutputStream dataOutputStream= new DataOutputStream(new BufferedOutputStream(os));
dataOutputStream.writeBytes(postData);
dataOutputStream.close();
}
FetchResult fetchResult = new FetchResult();
fetchResult.responseCode = urlConnection.getResponseCode();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder responseBuilder = new StringBuilder();
char[] buffer = new char[4096];
int amount = 0;
while ((amount = bufferedReader.read(buffer, 0,4096)) > 0) {
responseBuilder.append(String.valueOf(buffer, 0, amount));
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Response code " + urlConnection.getResponseCode() + " from " + urlStr);
}
// The alternative is to return multiple
fetchResult.response = responseBuilder.toString();
// Capture normalized headers
Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
fetchResult.responseHeaders = new HashMap<>();
for (String key: responseHeaders.keySet()) {
fetchResult.responseHeaders.put(key != null ? key.toUpperCase() : key, responseHeaders.get(key));
}
return fetchResult;
}
static enum HeaderMatchType { EQUALS, STARTSWITH, ENDSWITH };
static class HeaderMatch {
HeaderMatchType type;
String value;
static List<HeaderMatch> jsonHeaderMatchTypes;
static {
jsonHeaderMatchTypes = new ArrayList<>();
jsonHeaderMatchTypes.add(new URLUtil.HeaderMatch(URLUtil.HeaderMatchType.EQUALS, "application/json"));
jsonHeaderMatchTypes.add(new URLUtil.HeaderMatch(URLUtil.HeaderMatchType.ENDSWITH, "+json"));
}
HeaderMatch(HeaderMatchType type, String value) {
this.type = type;
this.value = value;
}
}
/**
* Tries to find see if a particular
* @param headers
* @param key header to match against
* @param headerMatches header match expressions to test against
* @param delimiter
* @return
*/
static boolean headersContain(Map<String, List<String>> headers, String key, List<HeaderMatch> headerMatches, String delimiter) {
List<String> contentTypes = headers.get(key.toUpperCase());
if (contentTypes == null) {
return false;
}
boolean match = false;
for (String contentType: contentTypes) {
String [] contentTypeStrs;
if (delimiter != null && delimiter.length() > 0) {
contentTypeStrs = contentType.split(delimiter);
}
else {
contentTypeStrs = new String[1];
contentTypeStrs[0] = contentType;
}
for (String contentTypeStr: contentTypeStrs) {
for (HeaderMatch headerMatch: headerMatches) {
switch(headerMatch.type) {
case EQUALS:
if (contentTypeStr.trim().equals(headerMatch.value)) {
match = true;
}
break;
case STARTSWITH:
if (contentTypeStr.startsWith(headerMatch.value)) {
match = true;
}
break;
case ENDSWITH:
if (contentTypeStr.endsWith(headerMatch.value)) {
match = true;
}
break;
}
if (match) {
break;
}
}
}
if (match) {
break;
}
}
return match;
}
public static Map<String, String> parseQueryString(String queryString) throws QueryParsingException {
Map<String, String> parameters = new HashMap<>();
if (queryString == null) {
return parameters;
}
String[] pairs = queryString.split("&");
try {
for (String pair : pairs) {
int idx = pair.indexOf('=');
if (idx < 0) {
throw new BigDawgCatalogException("Could not find '=' in param pair: " + pair);
}
String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
String value = "";
if (idx < pair.length() - 1) {
value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
}
if (parameters.containsKey(key)) {
throw new BigDawgCatalogException("Redundant parameter '" + key + "'");
}
parameters.put(key, value);
}
}
catch (Exception e) {
throw new QueryParsingException(e.getMessage());
}
return parameters;
}
public static String encodeParameters(Map<String, String> parameters) {
StringJoiner joiner = new StringJoiner("&");
parameters.forEach((k, v) -> {
joiner.add(URLUtil.percentEncode(k) + "=" + URLUtil.percentEncode(v));
});
return joiner.toString();
}
public static Map<String, String> decodeParameters(String parameters) throws ParseException {
Map<String, String> parametersMap = new HashMap<>();
if (parameters == null) {
return parametersMap;
}
String[] pairs = parameters.split("&");
try {
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length < 2) {
throw new ParseException("Could not parse parameters, one pair does not have key=value format: " + pair, -1);
} else if (parts.length > 2) {
throw new ParseException("Could not parse parameters, one pair of key=value has more than one '=': " + pair, -1);
}
parametersMap.put(URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8"));
}
}
catch (UnsupportedEncodingException e) {
throw new ParseException(e.toString(), -1);
}
return parametersMap;
}
static String appendQueryParameters(String url, Map<String, String> parameters) {
if (parameters == null || parameters.isEmpty()) {
return url;
}
return appendQueryParameters(url, encodeParameters(parameters));
}
static String appendQueryParameters(String url, String queryParams) {
if (queryParams == null) {
return url;
}
StringBuilder sb = new StringBuilder();
sb.append(url);
if (!url.contains("?")) {
sb.append("?");
}
else {
sb.append("&");
}
sb.append(queryParams);
return sb.toString();
}
}
|
package com.example.yeelin.homework2.h312yeelin.service;
import android.content.ContentValues;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.example.yeelin.homework2.h312yeelin.networkUtils.FetchDataUtils;
import com.example.yeelin.homework2.h312yeelin.provider.BaseWeatherContract;
import com.example.yeelin.homework2.h312yeelin.provider.CurrentWeatherContract;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class FindCityDataHelper {
private static final String TAG = FindCityDataHelper.class.getCanonicalName();
//middle uri parts
private static final String PATH_FIND = "find";
private static final String QUERY_CITY_LATITUDE = "lat";
private static final String QUERY_CITY_LONGITUDE = "lon";
private static final String QUERY_COUNT = "cnt";
private static final int QUERY_CITY_COUNT = 10;
/**
* Uses the given lat/long to query open weather's find api. The cityName is used to match against the
* city name in the response to get a more accurate city.
* @param cityName
* @param latitude
* @param longitude
* @return cityId
*/
public static long findCityId(@Nullable String cityName, double latitude, double longitude) {
try {
final URL url = buildUrl(latitude, longitude);
final HttpURLConnection urlConnection = FetchDataUtils.performGet(url);
final ArrayList<ContentValues> valuesArrayList = buildContentValues(urlConnection);
if (valuesArrayList != null && valuesArrayList.size() > 0) {
if (cityName == null) {
//cityName is null so just pick the first one and go with it
final ContentValues values = valuesArrayList.get(0);
Log.d(TAG, "findCityId: CityName is null so returning the first city:" + values.getAsString(CurrentWeatherContract.Columns.CITY_NAME));
return values.getAsLong(CurrentWeatherContract.Columns.CITY_ID);
}
//cityName is not null, so check each ContentValues map to see if there's a match for city name
final String cityNameInLowercase = cityName.toLowerCase();
for (ContentValues values : valuesArrayList) {
final String candidateCityNameInLowercase = values.getAsString(CurrentWeatherContract.Columns.CITY_NAME).toLowerCase();
if (cityNameInLowercase.equals(candidateCityNameInLowercase) ||
cityNameInLowercase.contains(candidateCityNameInLowercase) ||
candidateCityNameInLowercase.contains(cityNameInLowercase)) {
//we found a match
Log.d(TAG, String.format("findCityId: We found a match. cityName:%s, candidateCityName:%s", cityNameInLowercase, candidateCityNameInLowercase));
return values.getAsLong(CurrentWeatherContract.Columns.CITY_ID);
}
}
}
}
catch (MalformedURLException e) {
Log.e(TAG, "findCityId: Unexpected error:", e);
}
catch (IOException e) {
Log.e(TAG, "findCityId: Unexpected error:", e);
}
Log.d(TAG, String.format("findCityId: Could not find cityId for cityName:%s (%f, %f)", cityName, latitude, longitude));
return BaseWeatherContract.NO_ID;
}
@NonNull
public static URL buildUrl(double latitude, double longitude) throws MalformedURLException {
Log.d(TAG, "buildUrl: LatLong: " + latitude + ", " + longitude);
//header
Uri.Builder uriBuilder = FetchDataUtils.getHeaderForUriBuilder();
//middle
appendMiddleToUriBuilder(uriBuilder, latitude, longitude);
//footer
uriBuilder = FetchDataUtils.appendFooterToUriBuilder(uriBuilder);
//convert uri builder into a URL
return FetchDataUtils.buildUrl(uriBuilder);
}
/**
* Appends the middle part to the given uri builder and returns it
* @param uriBuilder
* @param latitude
* @param longitude
* @return
*/
@NonNull
private static Uri.Builder appendMiddleToUriBuilder(@NonNull Uri.Builder uriBuilder, double latitude, double longitude) {
uriBuilder.appendPath(PATH_FIND)
.appendQueryParameter(QUERY_CITY_LATITUDE, Double.toString(latitude))
.appendQueryParameter(QUERY_CITY_LONGITUDE, Double.toString(longitude))
.appendQueryParameter(QUERY_COUNT, Integer.toString(QUERY_CITY_COUNT));
return uriBuilder;
}
/**
* Processes the multi city response from the group API into content values for insertion into current_weather table.
* @param urlConnection
* @return
* @throws java.io.IOException
*/
public static ArrayList<ContentValues> buildContentValues(@NonNull HttpURLConnection urlConnection) throws IOException {
Log.d(TAG, "buildContentValues");
return GroupCurrentWeatherDataHelper.buildContentValues(urlConnection);
}
}
|
package mho.qbar.objects;
import mho.haskellesque.math.MathUtils;
import mho.haskellesque.numbers.Numbers;
import mho.haskellesque.ordering.Ordering;
import mho.haskellesque.structures.Pair;
import mho.haskellesque.structures.Triple;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import static mho.haskellesque.iterables.IterableUtils.*;
import static mho.haskellesque.ordering.Ordering.*;
public final class Rational implements Comparable<Rational> {
public static final @NotNull Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);
public static final @NotNull Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE);
public static final @NotNull Rational SMALLEST_FLOAT = new Rational(BigInteger.ONE, BigInteger.ONE.shiftLeft(149));
public static final @NotNull Rational LARGEST_SUBNORMAL_FLOAT =
new Rational(BigInteger.ONE.shiftLeft(23).subtract(BigInteger.ONE), BigInteger.ONE.shiftLeft(149));
public static final @NotNull Rational SMALLEST_NORMAL_FLOAT =
new Rational(BigInteger.ONE, BigInteger.ONE.shiftLeft(126));
public static final @NotNull Rational LARGEST_FLOAT =
new Rational(BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE.shiftLeft(104)), BigInteger.ONE);
public static final @NotNull Rational SMALLEST_DOUBLE =
new Rational(BigInteger.ONE, BigInteger.ONE.shiftLeft(1074));
public static final @NotNull Rational LARGEST_SUBNORMAL_DOUBLE =
new Rational(BigInteger.ONE.shiftLeft(52).subtract(BigInteger.ONE), BigInteger.ONE.shiftLeft(1074));
public static final @NotNull Rational SMALLEST_NORMAL_DOUBLE =
new Rational(BigInteger.ONE, BigInteger.ONE.shiftLeft(1022));
public static final @NotNull Rational LARGEST_DOUBLE =
new Rational(BigInteger.ONE.shiftLeft(1024).subtract(BigInteger.ONE.shiftLeft(971)), BigInteger.ONE);
/**
* {@code this} times {@code denominator}
*/
private final @NotNull BigInteger numerator;
private final @NotNull BigInteger denominator;
/**
* Private constructor from {@link BigInteger}s; assumes arguments are valid
*
* <ul>
* <li>{@code numerator} cannot be null.</li>
* <li>{@code denominator} cannot be null or equal to 0.</li>
* <li>{@code numerator} and {@code denominator} cannot have a positive common factor greater than 1.</li>
* <li>Any {@code Rational} may be constructed with this constructor.</li>
* </ul>
*
* @param numerator the numerator
* @param denominator the denominator
*/
private Rational(@NotNull BigInteger numerator, @NotNull BigInteger denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
/**
* Returns this {@code Rational}'s numerator
*
* <ul>
* <li>The result is non-null.</li>
* </ul>
*
* @return the numerator
*/
public @NotNull BigInteger getNumerator() {
return numerator;
}
/**
* Returns this {@code Rational}'s denominator
*
* <ul>
* <li>The result is positive.</li>
* </ul>
*
* @return the denominator
*/
public @NotNull BigInteger getDenominator() {
return denominator;
}
/**
* Creates a {@code Rational} from {@code BigInteger}s. Throws an exception if {@code denominator} is zero. Reduces
* arguments and negates denominator if necessary.
*
* <ul>
* <li>{@code numerator} cannot be null.</li>
* <li>{@code denominator} cannot be null or equal to 0.</li>
* <li>The result is non-null.</li>
* </ul>
*
* @param numerator the numerator
* @param denominator the denominator
* @return the {@code Rational} corresponding to {@code numerator}/{@code denominator}
* @throws java.lang.ArithmeticException if denominator is zero
*/
public static @NotNull Rational of(@NotNull BigInteger numerator, @NotNull BigInteger denominator) {
if (denominator.equals(BigInteger.ZERO))
throw new ArithmeticException("division by zero");
if (numerator.equals(BigInteger.ZERO)) return ZERO;
if (numerator.equals(denominator)) return ONE;
BigInteger gcd = numerator.gcd(denominator);
if (denominator.signum() < 0) gcd = gcd.negate();
return new Rational(numerator.divide(gcd), denominator.divide(gcd));
}
public static @NotNull Rational of(int numerator, int denominator) {
if (denominator == 0)
throw new ArithmeticException("division by zero");
if (numerator == 0) return ZERO;
if (numerator == denominator) return ONE;
int gcd = MathUtils.gcd(numerator, denominator);
if (denominator < 0) gcd = -gcd;
return new Rational(BigInteger.valueOf(numerator / gcd), BigInteger.valueOf(denominator / gcd));
}
/**
* Creates a {@code Rational} from a {@code BigInteger}.
*
* <ul>
* <li>{@code n} cannot be null.</li>
* <li>The result is an integral {@code Rational}.</li>
* </ul>
*
* @param n the {@code BigInteger}
* @return the {@code Rational} corresponding to {@code n}
*/
public static @NotNull Rational of(@NotNull BigInteger n) {
if (n.equals(BigInteger.ZERO)) return ZERO;
if (n.equals(BigInteger.ONE)) return ONE;
return new Rational(n, BigInteger.ONE);
}
public static @NotNull Rational of(int n) {
if (n == 0) return ZERO;
if (n == 1) return ONE;
return new Rational(BigInteger.valueOf(n), BigInteger.ONE);
}
public static @Nullable Rational of(float f) {
if (f == 0.0f) return ZERO;
if (f == 1.0f) return ONE;
if (Float.isInfinite(f) || Float.isNaN(f)) return null;
int bits = Float.floatToIntBits(f);
int exponent = bits >> 23 & ((1 << 8) - 1);
int mantissa = bits & ((1 << 23) - 1);
Rational rational;
if (exponent == 0) {
rational = of(mantissa).shiftRight(149);
} else {
rational = of(mantissa + (1 << 23), 1 << 23).shiftLeft(exponent - 127);
}
if (bits < 0) rational = rational.negate();
return rational;
}
public static @Nullable Rational of(double d) {
if (d == 0.0) return ZERO;
if (d == 1.0) return ONE;
if (Double.isInfinite(d) || Double.isNaN(d)) return null;
long bits = Double.doubleToLongBits(d);
int exponent = (int) (bits >> 52) & ((1 << 11) - 1);
long mantissa = bits & ((1L << 52) - 1);
Rational rational;
if (exponent == 0) {
rational = of(BigInteger.valueOf(mantissa)).shiftRight(1074);
} else {
Rational significand = of(BigInteger.valueOf(mantissa)).shiftRight(52);
rational = add(significand, ONE).shiftLeft(exponent - 1023);
}
if (bits < 0) rational = rational.negate();
return rational;
}
public static @NotNull Rational of(@NotNull BigDecimal d) {
return divide(of(d.unscaledValue()), of(10).pow(d.scale()));
}
public @NotNull Rational negate() {
if (this == ZERO) return ZERO;
BigInteger negativeNumerator = numerator.negate();
if (negativeNumerator.equals(denominator)) return ONE;
return new Rational(negativeNumerator, denominator);
}
/**
* Returns the multiplicative inverse of {@code this}.
*
* <ul>
* <li>{@code this} may be any non-zero {@code Rational}.</li>
* <li>The result is a non-zero {@code Rational}.</li>
* </ul>
*
* @return 1/{@code this}.
*/
public @NotNull Rational invert() {
if (this == ZERO)
throw new ArithmeticException("division by zero");
if (equals(ONE)) return ONE;
if (numerator.signum() == -1) {
return new Rational(denominator.negate(), numerator.negate());
} else {
return new Rational(denominator, numerator);
}
}
/**
* Returns the absolute value of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code Rational.}</li>
* <li>The result is a non-negative {@code Rational}.</li>
* </ul>
*
* @return |{@code this}|.
*/
public @NotNull Rational abs() {
return numerator.signum() == -1 ? negate() : this;
}
public int signum() {
return numerator.signum();
}
/**
* Returns the sum of {@code a} and {@code b}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the first {@code Rational}
* @param b the second {@code Rational}
* @return {@code a}+{@code b}
*/
public static @NotNull Rational add(@NotNull Rational a, @NotNull Rational b) {
if (a == ZERO) return b;
if (b == ZERO) return a;
BigInteger d1 = a.denominator.gcd(b.denominator);
if (d1.equals(BigInteger.ONE)) {
BigInteger sn = a.numerator.multiply(b.denominator).add(a.denominator.multiply(b.numerator));
if (sn.equals(BigInteger.ZERO)) return ZERO;
BigInteger sd = a.denominator.multiply(b.denominator);
if (sn.equals(sd)) return ONE;
return new Rational(sn, sd);
} else {
BigInteger t = a.numerator.multiply(b.denominator.divide(d1))
.add(b.numerator.multiply(a.denominator.divide(d1)));
if (t.equals(BigInteger.ZERO)) return ZERO;
BigInteger d2 = t.gcd(d1);
BigInteger sn = t.divide(d2);
BigInteger sd = a.denominator.divide(d1).multiply(b.denominator.divide(d2));
if (sn.equals(sd)) return ONE;
return new Rational(sn, sd);
}
}
public static @NotNull Rational subtract(@NotNull Rational a, @NotNull Rational b) {
return add(a, b.negate());
}
public static @NotNull Rational multiply(@NotNull Rational a, @NotNull Rational b) {
if (a == ZERO || b == ZERO) return ZERO;
if (a == ONE) return b;
if (b == ONE) return a;
BigInteger g1 = a.numerator.gcd(b.denominator);
BigInteger g2 = b.numerator.gcd(a.denominator);
BigInteger mn = a.numerator.divide(g1).multiply(b.numerator.divide(g2));
BigInteger md = a.denominator.divide(g2).multiply(b.denominator.divide(g1));
if (mn.equals(md)) return ONE;
return new Rational(mn, md);
}
public @NotNull Rational multiply(@NotNull BigInteger that) {
if (this == ZERO || that.equals(BigInteger.ZERO)) return ZERO;
if (numerator.equals(BigInteger.ONE) && denominator.equals(that) ||
numerator.equals(BigInteger.ONE.negate()) && denominator.equals(that.negate())) return ONE;
BigInteger g = denominator.gcd(that);
return new Rational(numerator.multiply(that.divide(g)), denominator.divide(g));
}
public @NotNull Rational multiply(int that) {
if (this == ZERO || that == 0) return ZERO;
if (numerator.equals(BigInteger.ONE) && denominator.equals(BigInteger.valueOf(that))) return ONE;
if (numerator.equals(BigInteger.ONE.negate()) && denominator.equals(BigInteger.valueOf(that).negate()))
return ONE;
BigInteger g = denominator.gcd(BigInteger.valueOf(that));
return new Rational(numerator.multiply(BigInteger.valueOf(that).divide(g)), denominator.divide(g));
}
/**
* Returns the quotient of {@code a} and {@code b}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null or zero.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the first {@code Rational}
* @param b the second {@code Rational}
* @return {@code a}/{@code b}
*/
public static @NotNull Rational divide(@NotNull Rational a, @NotNull Rational b) {
if (b == ZERO)
throw new ArithmeticException("division by zero");
return multiply(a, b.invert());
}
/**
* Returns the quotient of {@code this} and {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code that} cannot be null or zero.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param that the divisor
* @return {@code this}/{@code that}
*/
public @NotNull Rational divide(@NotNull BigInteger that) {
if (that.equals(BigInteger.ZERO))
throw new ArithmeticException("division by zero");
if (this == ZERO) return ZERO;
if (denominator.equals(BigInteger.ONE) && numerator.equals(that)) return ONE;
BigInteger g = numerator.gcd(that);
if (that.signum() == -1) g = g.negate();
return new Rational(numerator.divide(g), denominator.multiply(that.divide(g)));
}
/**
* Returns the quotient of {@code this} and {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code that} cannot be zero.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param that the divisor
* @return {@code this}/{@code that}
*/
public @NotNull Rational divide(int that) {
if (that == 0)
throw new ArithmeticException("division by zero");
if (this == ZERO) return ZERO;
if (denominator.equals(BigInteger.ONE) && numerator.equals(BigInteger.valueOf(that))) return ONE;
BigInteger g = numerator.gcd(BigInteger.valueOf(that));
if (that < 0) g = g.negate();
return new Rational(numerator.divide(g), denominator.multiply(BigInteger.valueOf(that).divide(g)));
}
/**
* Returns {@code this} raised to the power of {@code p}. 0<sup>0</sup> yields 1.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code p} may be any {@code int}.</li>
* <li>If {@code p}{@literal <}0, {@code this} cannot be 0.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param p the power
* @return {@code this}<sup>{@code p}</sup>
*/
public @NotNull Rational pow(int p) {
if (p == 0) return ONE;
if (p == 1) return this;
if (p < 0) {
if (this == ZERO)
throw new ArithmeticException("division by zero");
return invert().pow(-p);
}
if (this == ZERO || this == ONE) return this;
if (this.equals(ONE.negate()) && p % 2 == 0) return ONE;
BigInteger pNumerator = numerator.pow(p);
BigInteger pDenominator = denominator.pow(p);
if (pDenominator.signum() == -1) {
pNumerator = pNumerator.negate();
pDenominator = pDenominator.negate();
}
return new Rational(pNumerator, pDenominator);
}
public @NotNull BigInteger floor() {
if (numerator.signum() < 0) {
return negate().ceiling().negate();
} else {
return numerator.divide(denominator);
}
}
public @NotNull BigInteger ceiling() {
if (numerator.signum() < 0) {
return negate().floor().negate();
} else {
if (numerator.mod(denominator).equals(BigInteger.ZERO)) {
return numerator.divide(denominator);
} else {
return numerator.divide(denominator).add(BigInteger.ONE);
}
}
}
public @NotNull Rational fractionalPart() {
if (denominator.equals(BigInteger.ONE)) return ZERO;
return subtract(this, of(floor()));
}
/**
* Rounds {@code this} to an integer according to {@code roundingMode}; see {@link java.math.RoundingMode} for
* details.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code roundingMode} may be any {@code RoundingMode}.</li>
* <li>If {@code roundingMode} is {@link java.math.RoundingMode#UNNECESSARY}, {@code this} must be an
* integer.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param roundingMode determines the way in which {@code this} is rounded. Options are
* {@link java.math.RoundingMode#UP}, {@link java.math.RoundingMode#DOWN}, {@link java.math.RoundingMode#CEILING},
* {@link java.math.RoundingMode#FLOOR}, {@link java.math.RoundingMode#HALF_UP},
* {@link java.math.RoundingMode#HALF_DOWN}, {@link java.math.RoundingMode#HALF_EVEN}, and
* {@link java.math.RoundingMode#UNNECESSARY}.
* @return {@code this}, rounded
*/
public @NotNull BigInteger round(@NotNull RoundingMode roundingMode) {
Ordering halfCompare = compare(fractionalPart(), of(1, 2));
if (signum() == -1) halfCompare = halfCompare.invert();
switch (roundingMode) {
case UNNECESSARY:
if (denominator.equals(BigInteger.ONE)) {
return numerator;
} else {
throw new ArithmeticException("Rational not an integer. Use a different rounding mode");
}
case FLOOR:
return floor();
case CEILING:
return ceiling();
case DOWN:
return numerator.divide(denominator);
case UP:
BigInteger down = numerator.divide(denominator);
if (numerator.mod(denominator).equals(BigInteger.ZERO)) {
return down;
} else {
if (numerator.signum() == 1) {
return down.add(BigInteger.ONE);
} else {
return down.subtract(BigInteger.ONE);
}
}
case HALF_DOWN:
if (halfCompare == GT) {
return round(RoundingMode.UP);
} else {
return round(RoundingMode.DOWN);
}
case HALF_UP:
if (halfCompare == LT) {
return round(RoundingMode.DOWN);
} else {
return round(RoundingMode.UP);
}
case HALF_EVEN:
if (halfCompare == LT) return round(RoundingMode.DOWN);
if (halfCompare == GT) return round(RoundingMode.UP);
BigInteger floor = floor();
return floor.testBit(0) ? floor.add(BigInteger.ONE) : floor;
}
return null; //never happens
}
//todo finish fixing JavaDoc
/**
* Rounds {@code this} a rational number that is an integer multiple of 1/{@code denominator} according to
* {@code roundingMode}; see documentation for {@code java.math.RoundingMode} for details.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code denominator} must be positive.</li>
* <li>If {@code roundingMode} is {@code UNNECESSARY}, {@code this}'s denominator must divide
* {@code denominator}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param denominator the denominator which represents the precision that {@code this} is rounded to.
* @param roundingMode determines the way in which {@code this} is rounded. Options are {@code UP},
* {@code DOWN}, {@code CEILING}, {@code FLOOR}, {@code HALF_UP}, {@code HALF_DOWN},
* {@code HALF_EVEN}, and {@code UNNECESSARY}.
* @return {@code this}, rounded to an integer multiple of 1/{@code denominator}
*/
public @NotNull Rational roundToDenominator(@NotNull BigInteger denominator, @NotNull RoundingMode roundingMode) {
if (denominator.signum() != 1)
throw new ArithmeticException("must round to a positive denominator");
return of(multiply(denominator).round(roundingMode)).divide(denominator);
}
/**
* Returns the left shift of {@code this} by {@code bits};
* {@code this}×2<sup>{@code bits}</sup>. Negative {@code bits} corresponds to a right shift.
*
* <ul>
* <li>{@code this} can be any {@code Rational}.</li>
* <li>{@code bits} may be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param bits the number of bits to left-shift by
* @return {@code this}<<{@code bits}
*/
public @NotNull Rational shiftLeft(int bits) {
if (this == ZERO) return ZERO;
if (bits == 0) return this;
if (bits < 0) return shiftRight(-bits);
int denominatorTwos = denominator.getLowestSetBit();
if (bits <= denominatorTwos) {
BigInteger shifted = denominator.shiftRight(bits);
if (numerator.equals(BigInteger.ONE) && shifted.equals(BigInteger.ONE)) return ONE;
return new Rational(numerator, shifted);
} else {
BigInteger shiftedNumerator = numerator.shiftLeft(bits - denominatorTwos);
BigInteger shiftedDenominator = denominator.shiftRight(denominatorTwos);
if (shiftedNumerator.equals(BigInteger.ONE) && shiftedDenominator.equals(BigInteger.ONE)) return ONE;
return new Rational(shiftedNumerator, shiftedDenominator);
}
}
public @NotNull Rational shiftRight(int bits) {
if (this == ZERO) return ZERO;
if (bits == 0) return this;
if (bits < 0) return shiftLeft(-bits);
int numeratorTwos = numerator.getLowestSetBit();
if (bits <= numeratorTwos) {
BigInteger shifted = numerator.shiftRight(bits);
if (shifted.equals(BigInteger.ONE) && denominator.equals(BigInteger.ONE)) return ONE;
return new Rational(shifted, denominator);
} else {
BigInteger shiftedNumerator = numerator.shiftRight(numeratorTwos);
BigInteger shiftedDenominator = denominator.shiftLeft(bits - numeratorTwos);
if (shiftedNumerator.equals(BigInteger.ONE) && shiftedDenominator.equals(BigInteger.ONE)) return ONE;
return new Rational(shiftedNumerator, shiftedDenominator);
}
}
/**
* This method returns the floor of the base-2 logarithm of {@code this}. In other words, every positive
* {@code Rational} may be written as a×2<sup>b</sup>, where a is a {@code Rational} such that
* 1≤a<2 and b is an integer; this method returns b.
*
* <ul>
* <li>{@code this} must be positive.</li>
* <li>The result could be any integer.</li>
* </ul>
*
* @return ⌊{@code log<sub>2</sub>this}⌋
*/
public int binaryExponent() {
if (this == ONE) return 0;
Rational adjusted = this;
int exponent = 0;
if (lt(numerator, denominator)) {
while (lt(adjusted.numerator, adjusted.denominator)) {
adjusted = adjusted.shiftLeft(1);
exponent
}
} else {
while (ge(adjusted.numerator, adjusted.denominator)) {
adjusted = adjusted.shiftRight(1);
exponent++;
}
exponent
}
return exponent;
}
/**
* Every {@code Rational}has a <i>left-neighboring {@code float}</i>, or the largest {@code float} that is less
* than or equal to the {@code Rational}; this {@code float} may be -Infinity. Likewise, every {@code Rational}
* has a <i>right-neighboring {@code float}</i>: the smallest {@code float} greater than or equal to the
* {@code Rational}. This float may be Infinity. If {@code this} is exactly equal to some {@code float}, the
* left- and right-neighboring {@code float}s will both be equal to that {@code float} and to each other. This
* method returns the pair made up of the left- and right-neighboring {@code float}s. If the left-neighboring
* {@code float} is a zero, it is a positive zero; if the right-neighboring {@code float} is a zero, it is a
* negative zero. The exception is when {@code this} is equal to zero; then both neighbors are positive zeroes.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result is a pair of {@code float}s that are either equal, or the second is the next-largest
* {@code float} after the first. Negative zero may not appear in the first slot of the pair, and positive zero
* may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a
* NaN.</li>
* </ul>
*
* @return The pair of left- and right-neighboring {@code float}s.
*/
private @NotNull Pair<Float, Float> floatRange() {
if (this == ZERO) return new Pair<>(0f, 0f);
if (numerator.signum() == -1) {
Pair<Float, Float> negativeRange = negate().floatRange();
assert negativeRange.a != null;
assert negativeRange.b != null;
return new Pair<>(-negativeRange.b, -negativeRange.a);
}
int exponent = binaryExponent();
if (exponent > 127 || exponent == 127 && gt(this, LARGEST_FLOAT)) {
return new Pair<>(Float.MAX_VALUE, Float.POSITIVE_INFINITY);
}
Rational fraction;
int adjustedExponent;
if (exponent < -126) {
fraction = shiftLeft(149);
adjustedExponent = 0;
} else {
fraction = subtract(shiftRight(exponent), ONE).shiftLeft(23);
adjustedExponent = exponent + 127;
}
float loFloat = Float.intBitsToFloat((adjustedExponent << 23) + fraction.floor().intValueExact());
float hiFloat = fraction.denominator.equals(BigInteger.ONE) ? loFloat : Numbers.successor(loFloat);
return new Pair<>(loFloat, hiFloat);
}
/**
* Every {@code Rational}has a <i>left-neighboring {@code double}</i>, or the largest {@code double} that is
* less than or equal to the {@code Rational}; this {@code double} may be -Infinity. Likewise, every
* {@code Rational} has a <i>right-neighboring {@code double}</i>: the smallest {@code double} greater than or
* equal to the {@code Rational}. This double may be Infinity. If {@code this} is exactly equal to some
* {@code double}, the left- and right-neighboring {@code double}s will both be equal to that {@code double} and
* to each other. This method returns the pair made up of the left- and right-neighboring {@code double}s. If the
* left-neighboring {@code double} is a zero, it is a positive zero; if the right-neighboring {@code double} is a
* zero, it is a negative zero. The exception is when {@code this} is equal to zero; then both neighbors are
* positive zeroes.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result is a pair of {@code double}s that are either equal, or the second is the next-largest
* {@code double} after the first. Negative zero may not appear in the first slot of the pair, and positive zero
* may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a
* NaN.</li>
* </ul>
*
* @return The pair of left- and right-neighboring {@code double}s.
*/
private @NotNull Pair<Double, Double> doubleRange() {
if (this == ZERO) return new Pair<>(0.0, 0.0);
if (numerator.signum() == -1) {
Pair<Double, Double> negativeRange = negate().doubleRange();
assert negativeRange.a != null;
assert negativeRange.b != null;
return new Pair<>(-negativeRange.b, -negativeRange.a);
}
int exponent = binaryExponent();
if (exponent > 1023 || exponent == 1023 && gt(this, LARGEST_DOUBLE)) {
return new Pair<>(Double.MAX_VALUE, Double.POSITIVE_INFINITY);
}
Rational fraction;
int adjustedExponent;
if (exponent < -1022) {
fraction = shiftLeft(1074);
adjustedExponent = 0;
} else {
fraction = subtract(shiftRight(exponent), ONE).shiftLeft(52);
adjustedExponent = exponent + 1023;
}
double loDouble = Double.longBitsToDouble(((long) adjustedExponent << 52) + fraction.floor().longValue());
double hiDouble = fraction.denominator.equals(BigInteger.ONE) ? loDouble : Numbers.successor(loDouble);
return new Pair<>(loDouble, hiDouble);
}
public float toFloat() {
return toFloat(RoundingMode.HALF_EVEN);
}
public float toFloat(@NotNull RoundingMode roundingMode) {
Pair<Float, Float> floatRange = floatRange();
assert floatRange.a != null;
assert floatRange.b != null;
if (floatRange.a.equals(floatRange.b)) return floatRange.a;
Rational loFloat = of(floatRange.a);
Rational hiFloat = of(floatRange.b);
if ((loFloat == null || hiFloat == null) && roundingMode == RoundingMode.UNNECESSARY) {
throw new ArithmeticException("Rational not exactly equal to a float. Use a different rounding mode");
}
if (loFloat == null) {
if (roundingMode == RoundingMode.FLOOR || roundingMode == RoundingMode.UP ||
roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) {
return Float.NEGATIVE_INFINITY;
} else {
return -Float.MAX_VALUE;
}
}
if (hiFloat == null) {
if (roundingMode == RoundingMode.CEILING || roundingMode == RoundingMode.UP ||
roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) {
return Float.POSITIVE_INFINITY;
} else {
return Float.MAX_VALUE;
}
}
Rational midway = add(loFloat, hiFloat).shiftRight(1);
Ordering midwayCompare = compare(this, midway);
switch (roundingMode) {
case UNNECESSARY:
throw new ArithmeticException("Rational not exactly equal to a float. Use a different rounding mode");
case FLOOR:
return floatRange.a;
case CEILING:
return floatRange.b;
case DOWN:
return floatRange.a < 0 ? floatRange.b : floatRange.a;
case UP:
return floatRange.a < 0 ? floatRange.a : floatRange.b;
case HALF_DOWN:
if (midwayCompare == EQ) return signum() == 1 ? floatRange.a : floatRange.b;
return midwayCompare == LT ? floatRange.a : floatRange.b;
case HALF_UP:
if (midwayCompare == EQ) return signum() == 1 ? floatRange.b : floatRange.a;
return midwayCompare == LT ? floatRange.a : floatRange.b;
case HALF_EVEN:
if (midwayCompare == LT) return floatRange.a;
if (midwayCompare == GT) return floatRange.b;
return (Float.floatToIntBits(floatRange.a) & 1) == 0 ? floatRange.a : floatRange.b;
}
return 0; //never happens
}
public double toDouble() {
return toDouble(RoundingMode.HALF_EVEN);
}
public double toDouble(@NotNull RoundingMode roundingMode) {
Pair<Double, Double> doubleRange = doubleRange();
assert doubleRange.a != null;
assert doubleRange.b != null;
if (doubleRange.a.equals(doubleRange.b)) return doubleRange.a;
Rational loDouble = of(doubleRange.a);
Rational hiDouble = of(doubleRange.b);
if ((loDouble == null || hiDouble == null) && roundingMode == RoundingMode.UNNECESSARY) {
throw new ArithmeticException("Rational not exactly equal to a double. Use a different rounding mode");
}
if (loDouble == null) {
if (roundingMode == RoundingMode.FLOOR || roundingMode == RoundingMode.UP ||
roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) {
return Double.NEGATIVE_INFINITY;
} else {
return -Double.MAX_VALUE;
}
}
if (hiDouble == null) {
if (roundingMode == RoundingMode.CEILING || roundingMode == RoundingMode.UP ||
roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) {
return Double.POSITIVE_INFINITY;
} else {
return Double.MAX_VALUE;
}
}
Rational midway = add(loDouble, hiDouble).shiftRight(1);
Ordering midwayCompare = compare(this, midway);
switch (roundingMode) {
case UNNECESSARY:
throw new ArithmeticException("Rational not exactly equal to a double. Use a different rounding mode");
case FLOOR:
return doubleRange.a;
case CEILING:
return doubleRange.b;
case DOWN:
return doubleRange.a < 0 ? doubleRange.b : doubleRange.a;
case UP:
return doubleRange.a < 0 ? doubleRange.a : doubleRange.b;
case HALF_DOWN:
if (midwayCompare == EQ) return signum() == 1 ? doubleRange.a : doubleRange.b;
return midwayCompare == LT ? doubleRange.a : doubleRange.b;
case HALF_UP:
if (midwayCompare == EQ) return signum() == 1 ? doubleRange.b : doubleRange.a;
return midwayCompare == LT ? doubleRange.a : doubleRange.b;
case HALF_EVEN:
if (midwayCompare == LT) return doubleRange.a;
if (midwayCompare == GT) return doubleRange.b;
return (Double.doubleToLongBits(doubleRange.a) & 1) == 0 ? doubleRange.a : doubleRange.b;
}
return 0; //never happens
}
/**
* Determines whether {@code this} has a terminating decimal expansion (that is, whether the denominator has no
* prime factors other than 2 or 5).
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @return whether {@code this} has a terminating decimal expansion
*/
public boolean hasTerminatingDecimalExpansion() {
BigInteger denominatorResidue = denominator.shiftRight(denominator.getLowestSetBit());
BigInteger five = BigInteger.valueOf(5);
while (denominatorResidue.mod(five).equals(BigInteger.ZERO)) {
denominatorResidue = denominatorResidue.divide(five);
}
return denominatorResidue.equals(BigInteger.ONE);
}
/**
* Returns a BigDecimal exactly equal to {@code this}. Throws an {@code ArithmeticException} if {@code this}
* cannot be represented as a terminating decimal.
*
* <ul>
* <li>{@code this} must be a {@code Rational} whose decimal expansion is terminating; that is, its denominator
* must only have 2 or 5 as prime factors.</li>
* <li>The result is a {@code BigDecimal} with minimal scale. That is, the scale is the smallest non-negative n
* such that {@code this}×10<sup>n</sup> is an integer.</li>
* </ul>
*
* @return {@code this}, in {@code BigDecimal} form
*/
public @NotNull BigDecimal toBigDecimal() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator));
}
/**
* Rounds {@code this} to a {@code BigDecimal} with a specified precision (number of significant digits), or to
* full precision if {@code precision} is 0.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code precision} must be non-negative.</li>
* <li>If {@code precision} is 0, then {@code this} must be a {@code Rational} whose decimal expansion is
* terminating; that is, its denominator must only have 2 or 5 as prime factors.</li>
* <li>The result is a {@code BigDecimal} x such that x's scale is greater than or equal to zero and less than or
* equal to n, where n is the smallest non-negative integer such that x×10<sup>n</sup> is an integer.</li>
* </ul>
*
* @param precision the precision with which to round {@code this}. 0 indicates full precision.
* @return {@code this}, in {@code BigDecimal} form
*/
public @NotNull BigDecimal toBigDecimal(int precision) {
MathContext context = new MathContext(precision);
return new BigDecimal(numerator).divide(new BigDecimal(denominator), context);
}
/**
* Rounds {@code this} to a {@code BigDecimal} with a specified rounding mode (see documentation for
* {@code java.math.RoundingMode} for details) and with a specified precision (number of significant digits), or
* to full precision if {@code precision} is 0.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code precision} must be non-negative.</li>
* <li>{@code roundingMode} may be any {@code RoundingMode}.</li>
* <li>If {@code precision} is 0, then {@code this} must be a {@code Rational} whose decimal expansion is
* terminating; that is, its denominator must only have 2 or 5 as prime factors.</li>
* <li>If {@code roundingMode} is {@code UNNECESSARY}, then {@code precision} must be at least as large as the
* number of digits in {@code this}'s decimal expansion.</li>
* <li>The result is a {@code BigDecimal} x such that x's scale is greater than or equal to zero and less than or
* equal to n, where n is the smallest non-negative integer such x×10<sup>n</sup> is an integer.</li>
* </ul>
*
* @param precision the precision with which to round {@code this}. 0 indicates full precision.
* @param roundingMode specifies the details of how to round {@code this}.
* @return {@code this}, in {@code BigDecimal} form
*/
public @NotNull BigDecimal toBigDecimal(int precision, @NotNull RoundingMode roundingMode) {
MathContext context = new MathContext(precision, roundingMode);
return new BigDecimal(numerator).divide(new BigDecimal(denominator), context);
}
/**
* Finds the continued fraction of {@code this}. If we pretend that the result is an array called a of length n,
* then {@code this}=a[0]+1/(a[1]+1/(a[2]+...+1/a[n-1]...)). Every rational number has two such representations;
* this method returns the shortest one.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result is non-null and non-empty. The first element may be any {@code BigInteger}; the remaining
* elements, if any, are all positive. If the result has more than one element, the last element is greater than
* 1.</li>
* </ul>
*
* @return the continued-fraction-representation of {@code this}
*/
public @NotNull List<BigInteger> continuedFraction() {
List<BigInteger> continuedFraction = new ArrayList<>();
Rational remainder = this;
while (true) {
BigInteger floor = remainder.floor();
continuedFraction.add(floor);
remainder = subtract(remainder, of(floor));
if (remainder == ZERO) break;
remainder = remainder.invert();
}
return continuedFraction;
}
/**
* Returns the {@code Rational} corresponding to a continued fraction. Every rational number has two continued-
* fraction representations; either is accepted.
*
* <ul>
* <li>{@code continuedFraction} must be non-null and non-empty. All elements but the first must be
* positive.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param continuedFraction a continued fraction
* @return a[0]+1/(a[1]+1/(a[2]+...+1/a[n-1]...))
*/
public static @NotNull Rational fromContinuedFraction(@NotNull List<BigInteger> continuedFraction) {
Rational x = of(continuedFraction.get(continuedFraction.size() - 1));
for (int i = continuedFraction.size() - 2; i >= 0; i
if (i != 0 && continuedFraction.get(i).signum() != 1)
throw new IllegalArgumentException("all continued fraction elements but the first must be positive");
x = add(x.invert(), of(continuedFraction.get(i)));
}
return x;
}
/**
* Returns the convergents, or rational approximations of {@code this} formed by truncating its continued fraction
* at various points. The first element of the result is the floor of {@code this}, and the last element is
* {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result is a non-null, non-empty list that consists of the convergents of its last element.</li>
* </ul>
*
* @return the convergents of {@code this}.
*/
public @NotNull List<Rational> convergents() {
List<Rational> approximations = new ArrayList<>();
List<BigInteger> continuedFraction = continuedFraction();
for (int i = 0; i < continuedFraction.size(); i++) {
List<BigInteger> truncatedContinuedFraction = new ArrayList<>();
for (int j = 0; j <= i; j++) {
truncatedContinuedFraction.add(continuedFraction.get(j));
}
approximations.add(fromContinuedFraction(truncatedContinuedFraction));
}
return approximations;
}
/**
* Returns the positional expansion of (non-negative) {@code this} in a given base, in the form of a triple of
* {@code BigInteger} lists. The first list contains the digits before the decimal point, the second list contains
* the non-repeating part of the digits after the decimal point, and the third list contains the repeating digits.
* The digits are given in the usual order: most-significant first. The first two lists may be empty, but the third
* is always non-empty (if the digits terminate, the third list contains a single zero). The sign of {@code this}
* is ignored.
*
* <ul>
* <li>{@code this} must be non-negative.</li>
* <li>{@code base} must be greater than 1.</li>
* <li>The elements of the result are all non-null. The elements of the elements are all non-negative. The first
* element does not begin with a zero. The last element is non-empty. The second and third lists are minimal; that
* is, the sequence (second)(third)(third)(third)... cannot be represented in a more compact way. The lists [1, 2]
* and [3, 1, 2] are not minimal, because the sequence [1, 2, 3, 1, 2, 3, 1, 2, ...] can be represented by [] and
* [1, 2, 3]. The lists [] and [1, 2, 1, 2] are not minimal either, because the sequence
* [1, 2, 1, 2, 1, 2, ...] can be represented by [] and [1, 2].</li>
* </ul>
*
* @param base the base of the positional expansion
* @return a triple containing the digits before the decimal point, the non-repeating digits after the decimal
* point, and the repeating digits.
*/
public @NotNull Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>
positionalNotation(@NotNull BigInteger base) {
if (signum() == -1)
throw new IllegalArgumentException("this cannot be negative");
BigInteger floor = floor();
List<BigInteger> beforeDecimal = toList(MathUtils.digits(base, floor));
Rational fractionalPart = subtract(this, of(floor));
BigInteger numerator = fractionalPart.numerator;
BigInteger denominator = fractionalPart.denominator;
BigInteger remainder = numerator.multiply(base);
int index = 0;
Integer repeatingIndex;
List<BigInteger> digits = new ArrayList<>();
Map<BigInteger, Integer> remainders = new HashMap<>();
while (true) {
remainders.put(remainder, index);
BigInteger digit = remainder.divide(denominator);
digits.add(digit);
remainder = remainder.subtract(denominator.multiply(digit)).multiply(base);
repeatingIndex = remainders.get(remainder);
if (repeatingIndex != null) break;
index++;
}
List<BigInteger> nonrepeating = new ArrayList<>();
List<BigInteger> repeating = new ArrayList<>();
for (int i = 0; i < repeatingIndex; i++) {
nonrepeating.add(digits.get(i));
}
for (int i = repeatingIndex; i < digits.size(); i++) {
repeating.add(digits.get(i));
}
return new Triple<>(beforeDecimal, nonrepeating, repeating);
}
/**
* Creates a {@code Rational} from a base expansion.
*
* <ul>
* <li>{@code base} must be greater than 1.</li>
* <li>{@code beforeDecimalPoint} must only contain elements greater than or equal to zero and less than
* {@code base}.</li>
* <li>{@code nonRepeating} must only contain elements greater than or equal to zero and less than
* {@code base}.</li>
* <li>{@code repeating} must only contain elements greater than or equal to zero and less than
* {@code base}. It must also be non-empty; to input a terminating expansion, use one (or more) zeros.</li>
* </ul>
*
* @param base the base of the positional expansion
* @param beforeDecimalPoint the digits before the decimal point
* @param nonRepeating the non-repeating portion of the digits after the decimal point
* @param repeating the repeating portion of the digits after the decimal point
* @return (beforeDecimalPoint).(nonRepeating)(repeating)(repeating)(repeating)..._(base)
*/
public static @NotNull Rational fromPositionalNotation(
@NotNull BigInteger base,
@NotNull List<BigInteger> beforeDecimalPoint,
@NotNull List<BigInteger> nonRepeating,
@NotNull List<BigInteger> repeating
) {
BigInteger floor = MathUtils.fromDigits(base, beforeDecimalPoint);
BigInteger nonRepeatingInteger = MathUtils.fromDigits(base, nonRepeating);
BigInteger repeatingInteger = MathUtils.fromDigits(base, repeating);
Rational nonRepeatingPart = of(nonRepeatingInteger, base.pow(nonRepeating.size()));
Rational repeatingPart = of(repeatingInteger, base.pow(repeating.size()).subtract(BigInteger.ONE))
.divide(base.pow(nonRepeating.size()));
return add(add(of(floor), nonRepeatingPart), repeatingPart);
}
/**
* Returns the digits of (non-negative) {@code this} in a given base. The return value is a pair consisting of the
* digits before the decimal point (in a list) and the digits after the decimal point (in a possibly-infinite
* iterable). Trailing zeroes are not included.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code base} must be greater than 1.</li>
* <li>the result </li>
* </ul>
*
* @param base the base of the digits
* @return a pair consisting of the digits before the decimal point and the digits after
*/
public @NotNull Pair<List<BigInteger>, Iterable<BigInteger>> digits(BigInteger base) {
Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> positionalNotation = positionalNotation(base);
Iterable<BigInteger> afterDecimal;
assert positionalNotation.c != null;
if (positionalNotation.c.equals(Arrays.asList(BigInteger.ZERO))) {
afterDecimal = positionalNotation.b;
} else {
afterDecimal = concat(positionalNotation.b, cycle(positionalNotation.c));
}
return new Pair<>(positionalNotation.a, afterDecimal);
}
/**
* Determines whether {@code this} is equal to {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>{@code that} may be any {@code Object}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param that The {@code Rational} to be compared with {@code this}
* @return {@code this}={@code that}
*/
@Override
public boolean equals(Object that) {
if (this == that) return true;
if (that == null || Rational.class != that.getClass()) return false;
Rational r = (Rational) that;
return denominator.equals(r.denominator) && numerator.equals(r.numerator);
}
/**
* Calculates the hash code of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>(conjecture) The result may be any {@code int}.</li>
* </ul>
*
* @return {@code this}'s hash code.
*/
@Override
public int hashCode() {
return 31 * numerator.hashCode() + denominator.hashCode();
}
@Override
public int compareTo(@NotNull Rational that) {
return numerator.multiply(that.denominator).compareTo(that.numerator.multiply(denominator));
}
/**
* Creates a {@code Rational} from a {@code String}. Valid strings are of the form {@code a.toString()} or
* {@code a.toString() + "/" + b.toString()}, where {@code a} and {@code b} are some {@code BigInteger}s. If
* the {@code String} is invalid, the method returns Optional.empty() without throwing an exception; this aids
* composability.
*
* <ul>
* <li>{@code s} cannot be null and cannot be of the form {@code n.toString() + "/0"}, where {@code n} is some
* {@code BigInteger}.</li>
* <li>The result may contain any {@code Rational}, or be empty.</li>
* </ul>
*
* @param s a string representation of a {@code Rational}.
* @return the {@code Rational} represented by {@code s}, or null if {@code s} is invalid.
*/
public static @NotNull Optional<Rational> read(@NotNull String s) {
if (s.isEmpty()) return Optional.empty();
int slashIndex = s.indexOf("/");
if (slashIndex == -1) {
Optional<BigInteger> n = Numbers.readBigInteger(s);
return n.map(Rational::of);
} else {
Optional<BigInteger> numerator = Numbers.readBigInteger(s.substring(0, slashIndex));
if (!numerator.isPresent()) return Optional.empty();
Optional<BigInteger> denominator = Numbers.readBigInteger(s.substring(slashIndex + 1));
if (!denominator.isPresent()) return Optional.empty();
return Optional.of(of(numerator.get(), denominator.get()));
}
}
/**
* Creates a string representation of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code Rational}.</li>
* <li>The result is a string in one of two forms: {@code a.toString()} or {@code a.toString() + "/" +
* b.toString()}, where {@code a} and {@code b} are some {@code BigInteger}s such that {@code b} is
* positive and {@code a} and {@code b} have no positive common factors greater than 1.</li>
* </ul>
*
* @return a string representation of {@code this}.
*/
public @NotNull String toString() {
if (denominator.equals(BigInteger.ONE)) {
return numerator.toString();
} else {
return numerator.toString() + "/" + denominator.toString();
}
}
}
|
package net.fornwall.jelf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
public final class ElfFile {
/** Relocatable file type. A possible value of {@link #file_type}. */
public static final int FT_REL = 1;
/** Executable file type. A possible value of {@link #file_type}. */
public static final int FT_EXEC = 2;
/** Shared object file type. A possible value of {@link #file_type}. */
public static final int FT_DYN = 3;
/** Core file file type. A possible value of {@link #file_type}. */
public static final int FT_CORE = 4;
/** 32-bit objects. */
public static final byte CLASS_32 = 1;
/** 64-bit objects. */
public static final byte CLASS_64 = 2;
/** LSB data encoding. */
public static final byte DATA_LSB = 1;
/** MSB data encoding. */
public static final byte DATA_MSB = 2;
/** No architecture type. */
public static final int ARCH_NONE = 0;
/** AT&T architecture type. */
public static final int ARCH_ATT = 1;
/** SPARC architecture type. */
public static final int ARCH_SPARC = 2;
/** Intel 386 architecture type. */
public static final int ARCH_i386 = 3;
/** Motorola 68000 architecture type. */
public static final int ARCH_68k = 4;
/** Motorola 88000 architecture type. */
public static final int ARCH_88k = 5;
/** Intel 860 architecture type. */
public static final int ARCH_i860 = 7;
/** MIPS architecture type. */
public static final int ARCH_MIPS = 8;
public static final int ARCH_ARM = 0x28;
public static final int ARCH_X86_64 = 0x3E;
public static final int ARCH_AARCH64 = 0xB7;
/** Byte identifying the size of objects, either {@link #CLASS_32} or {link {@value #CLASS_64} . */
public final byte objectSize;
/**
* Returns a byte identifying the data encoding of the processor specific data. This byte will be either
* DATA_INVALID, DATA_LSB or DATA_MSB.
*/
public final byte encoding;
public final byte elfVersion;
/** Identifies the object file type. One of the FT_* constants in the class. */
public final short file_type; // Elf32_Half
/** The required architecture. One of the ARCH_* constants in the class. */
public final short arch; // Elf32_Half
/** Version */
public final int version; // Elf32_Word
/**
* Virtual address to which the system first transfers control. If there is no entry point for the file the value is
* 0.
*/
public final long entry_point; // Elf32_Addr
/** Program header table offset in bytes. If there is no program header table the value is 0. */
public final long ph_offset; // Elf32_Off
/** Section header table offset in bytes. If there is no section header table the value is 0. */
public final long sh_offset; // Elf32_Off
/** Processor specific flags. */
public int flags; // Elf32_Word
/** ELF header size in bytes. */
public short eh_size; // Elf32_Half
/** e_phentsize. Size of one entry in the file's program header table in bytes. All entries are the same size. */
public final short ph_entry_size; // Elf32_Half
/** e_phnum. Number of {@link ElfSegment} entries in the program header table, 0 if no entries. */
public final short num_ph; // Elf32_Half
/** Section header entry size in bytes. */
public final short sh_entry_size; // Elf32_Half
/** Number of entries in the section header table, 0 if no entries. */
public final short num_sh; // Elf32_Half
/**
* Elf{32,64}_Ehdr#e_shstrndx. Index into the section header table associated with the section name string table.
* SH_UNDEF if there is no section name string table.
*/
private short sh_string_ndx; // Elf32_Half
/** MemoizedObject array of section headers associated with this ELF file. */
private MemoizedObject<ElfSection>[] sectionHeaders;
/** MemoizedObject array of program headers associated with this ELF file. */
private MemoizedObject<ElfSegment>[] programHeaders;
/** Used to cache symbol table lookup. */
private ElfSection symbolTableSection;
/** Used to cache dynamic symbol table lookup. */
private ElfSection dynamicSymbolTableSection;
private ElfSection dynamicLinkSection;
/**
* Returns the section header at the specified index. The section header at index 0 is defined as being a undefined
* section.
*/
public ElfSection getSection(int index) throws ElfException, IOException {
return sectionHeaders[index].getValue();
}
/** Returns the section header string table associated with this ELF file. */
public ElfStringTable getSectionNameStringTable() throws ElfException, IOException {
return getSection(sh_string_ndx).getStringTable();
}
/** Returns the string table associated with this ELF file. */
public ElfStringTable getStringTable() throws ElfException, IOException {
return findStringTableWithName(ElfSection.STRING_TABLE_NAME);
}
/**
* Returns the dynamic symbol table associated with this ELF file, or null if one does not exist.
*/
public ElfStringTable getDynamicStringTable() throws ElfException, IOException {
return findStringTableWithName(ElfSection.DYNAMIC_STRING_TABLE_NAME);
}
private ElfStringTable findStringTableWithName(String tableName) throws ElfException, IOException {
// Loop through the section header and look for a section
// header with the name "tableName". We can ignore entry 0
// since it is defined as being undefined.
for (int i = 1; i < num_sh; i++) {
ElfSection sh = getSection(i);
if (tableName.equals(sh.getName())) return sh.getStringTable();
}
return null;
}
/** The {@link ElfSection#SHT_SYMTAB} section (of which there may be only one), if any. */
public ElfSection getSymbolTableSection() throws ElfException, IOException {
return (symbolTableSection != null) ? symbolTableSection : (symbolTableSection = getSymbolTableSection(ElfSection.SHT_SYMTAB));
}
/** The {@link ElfSection#SHT_DYNSYM} section (of which there may be only one), if any. */
public ElfSection getDynamicSymbolTableSection() throws ElfException, IOException {
return (dynamicSymbolTableSection != null) ? dynamicSymbolTableSection : (dynamicSymbolTableSection = getSymbolTableSection(ElfSection.SHT_DYNSYM));
}
/** The {@link ElfSection#SHT_DYNAMIC} section (of which there may be only one). Named ".dynamic". */
public ElfSection getDynamicLinkSection() throws IOException {
return (dynamicLinkSection != null) ? dynamicLinkSection : (dynamicLinkSection = getSymbolTableSection(ElfSection.SHT_DYNAMIC));
}
private ElfSection getSymbolTableSection(int type) throws ElfException, IOException {
for (int i = 1; i < num_sh; i++) {
ElfSection sh = getSection(i);
if (sh.type == type) return sh;
}
return null;
}
/** Returns the elf symbol with the specified name or null if one is not found. */
public ElfSymbol getELFSymbol(String symbolName) throws ElfException, IOException {
if (symbolName == null) return null;
// Check dynamic symbol table for symbol name.
ElfSection sh = getDynamicSymbolTableSection();
if (sh != null) {
int numSymbols = sh.getNumberOfSymbols();
for (int i = 0; i < Math.ceil(numSymbols / 2); i++) {
ElfSymbol symbol = sh.getELFSymbol(i);
if (symbolName.equals(symbol.getName())) {
return symbol;
} else if (symbolName.equals((symbol = sh.getELFSymbol(numSymbols - 1 - i)).getName())) {
return symbol;
}
}
}
// Check symbol table for symbol name.
sh = getSymbolTableSection();
if (sh != null) {
int numSymbols = sh.getNumberOfSymbols();
for (int i = 0; i < Math.ceil(numSymbols / 2); i++) {
ElfSymbol symbol = sh.getELFSymbol(i);
if (symbolName.equals(symbol.getName())) {
return symbol;
} else if (symbolName.equals((symbol = sh.getELFSymbol(numSymbols - 1 - i)).getName())) {
return symbol;
}
}
}
return null;
}
/**
* Returns the elf symbol with the specified address or null if one is not found. 'address' is relative to base of
* shared object for .so's.
*/
public ElfSymbol getELFSymbol(long address) throws ElfException, IOException {
// Check dynamic symbol table for address.
ElfSymbol symbol = null;
long value = 0L;
ElfSection sh = getDynamicSymbolTableSection();
if (sh != null) {
int numSymbols = sh.getNumberOfSymbols();
for (int i = 0; i < numSymbols; i++) {
symbol = sh.getELFSymbol(i);
value = symbol.value;
if (address >= value && address < value + symbol.size) return symbol;
}
}
// Check symbol table for symbol name.
sh = getSymbolTableSection();
if (sh != null) {
int numSymbols = sh.getNumberOfSymbols();
for (int i = 0; i < numSymbols; i++) {
symbol = sh.getELFSymbol(i);
value = symbol.value;
if (address >= value && address < value + symbol.size) return symbol;
}
}
return null;
}
public ElfSegment getProgramHeader(int index) throws IOException {
return programHeaders[index].getValue();
}
public static ElfFile fromStream(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int totalRead = 0;
byte[] buffer = new byte[8096];
boolean firstRead = true;
while (true) {
int readNow = in.read(buffer, totalRead, buffer.length - totalRead);
if (readNow == -1) {
return fromBytes(baos.toByteArray());
} else {
if (firstRead) {
// Abort early.
if (readNow < 4) {
throw new ElfException("Bad first read");
} else {
if (!(0x7f == buffer[0] && 'E' == buffer[1] && 'L' == buffer[2] && 'F' == buffer[3]))
throw new ElfException("Bad magic number for file");
}
firstRead = false;
}
baos.write(buffer, 0, readNow);
}
}
}
public static ElfFile fromFile(File file) throws ElfException, IOException {
byte[] buffer = new byte[(int) file.length()];
try (FileInputStream in = new FileInputStream(file)) {
int totalRead = 0;
while (totalRead < buffer.length) {
int readNow = in.read(buffer, totalRead, buffer.length - totalRead);
if (readNow == -1) {
throw new ElfException("Premature end of file");
} else {
totalRead += readNow;
}
}
}
return new ElfFile(new ByteArrayInputStream(buffer));
}
public static ElfFile fromBytes(byte[] buffer) throws ElfException, IOException {
return new ElfFile(new ByteArrayInputStream(buffer));
}
public ElfFile(MappedByteBuffer buffer, long startPosition) throws ElfException, IOException {
final ElfParser parser = new ElfParser(this, buffer, startPosition);
//Parsing is a shitty thing to do in constructors.
byte[] ident = new byte[16];
int bytesRead = parser.read(ident);
if (bytesRead != ident.length)
throw new ElfException("Error reading elf header (read " + bytesRead + "bytes - expected to read " + ident.length + "bytes)");
if (!(0x7f == ident[0] && 'E' == ident[1] && 'L' == ident[2] && 'F' == ident[3])) throw new ElfException("Bad magic number for file");
objectSize = ident[4];
if (!(objectSize == CLASS_32 || objectSize == CLASS_64)) throw new ElfException("Invalid object size class: " + objectSize);
encoding = ident[5];
if (!(encoding == DATA_LSB || encoding == DATA_MSB)) throw new ElfException("Invalid encoding: " + encoding);
elfVersion = ident[6];
if (elfVersion != 1) throw new ElfException("Invalid elf version: " + elfVersion);
// ident[7]; // EI_OSABI, target operating system ABI
// ident[8]; // EI_ABIVERSION, ABI version. Linux kernel (after at least 2.6) has no definition of it.
// ident[9-15] // EI_PAD, currently unused.
file_type = parser.readShort();
arch = parser.readShort();
version = parser.readInt();
entry_point = parser.readIntOrLong();
ph_offset = parser.readIntOrLong();
sh_offset = parser.readIntOrLong();
flags = parser.readInt();
eh_size = parser.readShort();
ph_entry_size = parser.readShort();
num_ph = parser.readShort();
sh_entry_size = parser.readShort();
num_sh = parser.readShort();
if (num_sh == 0) {
throw new ElfException("e_shnum is SHN_UNDEF(0), which is not supported yet"
+ " (the actual number of section header table entries is contained in the sh_size field of the section header at index 0)");
}
sh_string_ndx = parser.readShort();
if (sh_string_ndx == /* SHN_XINDEX= */0xffff) {
throw new ElfException("e_shstrndx is SHN_XINDEX(0xffff), which is not supported yet"
+ " (the actual index of the section name string table section is contained in the sh_link field of the section header at index 0)");
}
sectionHeaders = MemoizedObject.uncheckedArray(num_sh);
for (int i = 0; i < num_sh; i++) {
final long sectionHeaderOffset = sh_offset + (i * sh_entry_size);
sectionHeaders[i] = new MemoizedObject<ElfSection>() {
@Override
public ElfSection computeValue() throws ElfException, IOException {
return new ElfSection(parser, sectionHeaderOffset);
}
};
}
programHeaders = MemoizedObject.uncheckedArray(num_ph);
for (int i = 0; i < num_ph; i++) {
final long programHeaderOffset = ph_offset + (i * ph_entry_size);
programHeaders[i] = new MemoizedObject<ElfSegment>() {
@Override
public ElfSegment computeValue() throws IOException {
return new ElfSegment(parser, programHeaderOffset);
}
};
}
}
public ElfFile(ByteArrayInputStream baos) throws ElfException, IOException {
final ElfParser parser = new ElfParser(this, baos);
byte[] ident = new byte[16];
int bytesRead = parser.read(ident);
if (bytesRead != ident.length)
throw new ElfException("Error reading elf header (read " + bytesRead + "bytes - expected to read " + ident.length + "bytes)");
if (!(0x7f == ident[0] && 'E' == ident[1] && 'L' == ident[2] && 'F' == ident[3])) throw new ElfException("Bad magic number for file");
objectSize = ident[4];
if (!(objectSize == CLASS_32 || objectSize == CLASS_64)) throw new ElfException("Invalid object size class: " + objectSize);
encoding = ident[5];
if (!(encoding == DATA_LSB || encoding == DATA_MSB)) throw new ElfException("Invalid encoding: " + encoding);
elfVersion = ident[6];
if (elfVersion != 1) throw new ElfException("Invalid elf version: " + elfVersion);
// ident[7]; // EI_OSABI, target operating system ABI
// ident[8]; // EI_ABIVERSION, ABI version. Linux kernel (after at least 2.6) has no definition of it.
// ident[9-15] // EI_PAD, currently unused.
file_type = parser.readShort();
arch = parser.readShort();
version = parser.readInt();
entry_point = parser.readIntOrLong();
ph_offset = parser.readIntOrLong();
sh_offset = parser.readIntOrLong();
flags = parser.readInt();
eh_size = parser.readShort();
ph_entry_size = parser.readShort();
num_ph = parser.readShort();
sh_entry_size = parser.readShort();
num_sh = parser.readShort();
if (num_sh == 0) {
throw new ElfException("e_shnum is SHN_UNDEF(0), which is not supported yet"
+ " (the actual number of section header table entries is contained in the sh_size field of the section header at index 0)");
}
sh_string_ndx = parser.readShort();
if (sh_string_ndx == /* SHN_XINDEX= */0xffff) {
throw new ElfException("e_shstrndx is SHN_XINDEX(0xffff), which is not supported yet"
+ " (the actual index of the section name string table section is contained in the sh_link field of the section header at index 0)");
}
sectionHeaders = MemoizedObject.uncheckedArray(num_sh);
for (int i = 0; i < num_sh; i++) {
final long sectionHeaderOffset = sh_offset + (i * sh_entry_size);
sectionHeaders[i] = new MemoizedObject<ElfSection>() {
@Override
public ElfSection computeValue() throws ElfException, IOException {
return new ElfSection(parser, sectionHeaderOffset);
}
};
}
programHeaders = MemoizedObject.uncheckedArray(num_ph);
for (int i = 0; i < num_ph; i++) {
final long programHeaderOffset = ph_offset + (i * ph_entry_size);
programHeaders[i] = new MemoizedObject<ElfSegment>() {
@Override
public ElfSegment computeValue() throws IOException {
return new ElfSegment(parser, programHeaderOffset);
}
};
}
}
/** The interpreter specified by the {@link ElfSegment#PT_INTERP} program header, if any. */
public String getInterpreter() throws IOException {
for (int i = 0; i < programHeaders.length; i++) {
ElfSegment ph = programHeaders[i].getValue();
if (ph.type == ElfSegment.PT_INTERP) return ph.getIntepreter();
}
return null;
}
}
|
package info.nightscout.androidaps.plugins.Overview.Dialogs;
import android.content.Context;
import android.os.Bundle;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
public class NewCarbsDialog extends DialogFragment implements OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private static Logger log = LoggerFactory.getLogger(NewCarbsDialog.class);
private EditText foodText;
private NumberPicker editCarbs;
private TextView dateButton;
private TextView timeButton;
private Date initialEventTime;
private Date eventTime;
private Button fav1Button;
private Button fav2Button;
private Button fav3Button;
private static final double FAV1_DEFAULT = 5;
private static final double FAV2_DEFAULT = 10;
private static final double FAV3_DEFAULT = 20;
private CheckBox suspendLoopCheckbox;
private CheckBox startActivityTTCheckbox;
private CheckBox startEatingSoonTTCheckbox;
private Integer maxCarbs;
//one shot guards
private boolean accepted;
private boolean okClicked;
public NewCarbsDialog() {
HandlerThread mHandlerThread = new HandlerThread(NewCarbsDialog.class.getSimpleName());
mHandlerThread.start();
}
final private TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateInputs();
}
};
private void validateInputs() {
Integer carbs = SafeParse.stringToInt(editCarbs.getText());
if (carbs > maxCarbs) {
editCarbs.setValue(0d);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.carbsconstraintapplied));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.overview_newcarbs_dialog, container, false);
view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
foodText = view.findViewById(R.id.newcarb_food);
editCarbs = view.findViewById(R.id.newcarb_carbsamount);
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher);
startActivityTTCheckbox = view.findViewById(R.id.newcarbs_activity_tt);
startEatingSoonTTCheckbox = view.findViewById(R.id.carbs_eating_soon_tt);
dateButton = view.findViewById(R.id.newcarbs_eventdate);
timeButton = view.findViewById(R.id.newcarb_eventtime);
initialEventTime = new Date();
eventTime = new Date(initialEventTime.getTime());
dateButton.setText(DateUtil.dateString(eventTime));
timeButton.setText(DateUtil.timeString(eventTime));
dateButton.setOnClickListener(this);
timeButton.setOnClickListener(this);
//To be able to select only one TT at a time
startEatingSoonTTCheckbox.setOnClickListener(this);
startActivityTTCheckbox.setOnClickListener(this);
// TODO prefilling carbs, maybe
// TODO maybe update suggested carbs to target TT when checked
// APSResult lastAPSResult = ConfigBuilderPlugin.getActiveAPS().getLastAPSResult();
// if (lastAPSResult != null && lastAPSResult instanceof DetermineBasalResultSMB && ((DetermineBasalResultSMB) lastAPSResult).carbsReq > 0) {
// editCarbs.setValue(((DetermineBasalResultSMB) lastAPSResult).carbsReq);
fav1Button = view.findViewById(R.id.newcarbs_plus1);
fav1Button.setOnClickListener(this);
fav1Button.setText("+" + SP.getString(R.string.key_carbs_button_increment_1, String.valueOf(FAV1_DEFAULT)));
fav2Button = view.findViewById(R.id.newcarbs_plus2);
fav2Button.setOnClickListener(this);
fav2Button.setText("+" + SP.getString(R.string.key_carbs_button_increment_2, String.valueOf(FAV2_DEFAULT)));
fav3Button = view.findViewById(R.id.newcarbs_plus3);
fav3Button.setOnClickListener(this);
fav3Button.setText("+" + SP.getString(R.string.key_carbs_button_increment_3, String.valueOf(FAV3_DEFAULT)));
suspendLoopCheckbox = view.findViewById(R.id.newcarbs_suspend_loop);
setCancelable(true);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
@Override
public synchronized void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventTime);
switch (view.getId()) {
case R.id.ok:
submit();
break;
case R.id.cancel:
dismiss();
break;
case R.id.newcarbs_eventdate:
DatePickerDialog dpd = DatePickerDialog.newInstance(
this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setThemeDark(true);
dpd.dismissOnPause(true);
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
break;
case R.id.newcarb_eventtime:
TimePickerDialog tpd = TimePickerDialog.newInstance(
this,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(getActivity())
);
tpd.setThemeDark(true);
tpd.dismissOnPause(true);
tpd.show(getActivity().getFragmentManager(), "Timepickerdialog");
break;
case R.id.newcarbs_plus1:
editCarbs.setValue(editCarbs.getValue()
+ SP.getDouble(R.string.key_carbs_button_increment_1, FAV1_DEFAULT));
validateInputs();
break;
case R.id.newcarbs_plus2:
editCarbs.setValue(editCarbs.getValue()
+ SP.getDouble(R.string.key_carbs_button_increment_2, FAV2_DEFAULT));
validateInputs();
break;
case R.id.newcarbs_plus3:
editCarbs.setValue(editCarbs.getValue()
+ SP.getDouble(R.string.key_carbs_button_increment_3, FAV3_DEFAULT));
validateInputs();
break;
case R.id.newcarbs_activity_tt:
startEatingSoonTTCheckbox.setChecked(false);
break;
case R.id.carbs_eating_soon_tt:
startActivityTTCheckbox.setChecked(false);
break;
}
}
private void submit() {
if (okClicked) {
log.debug("guarding: ok already clicked");
dismiss();
return;
}
okClicked = true;
try {
final String food = StringUtils.trimToNull(foodText.getText().toString());
final Integer carbs = SafeParse.stringToInt(editCarbs.getText());
Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(carbs);
String confirmMessage = "";
if (carbs > 0)
confirmMessage += MainApp.gs(R.string.carbs) + ": " + "<font color='" + MainApp.gc(R.color.colorCarbsButton) + "'>" + carbsAfterConstraints + "g" + "</font>";
if (!carbsAfterConstraints.equals(carbs))
confirmMessage += "<br/><font color='" + MainApp.gc(R.color.low) + "'>" + MainApp.gs(R.string.carbsconstraintapplied) + "</font>";
if (suspendLoopCheckbox.isChecked()) {
confirmMessage += "<br/>" + MainApp.gs(R.string.loop) + ": " + "<font color='" + MainApp.gc(R.color.low) + "'>" + MainApp.gs(R.string.suspendloopfor30min) + "</font>";
}
final Profile currentProfile = MainApp.getConfigBuilder().getProfile();
if (currentProfile == null)
return;
int activityTTDuration = SP.getInt(R.string.key_activity_duration, Constants.defaultActivityTTDuration);
activityTTDuration = activityTTDuration > 0 ? activityTTDuration : Constants.defaultActivityTTDuration;
double activityTT = SP.getDouble(R.string.key_activity_target, currentProfile.getUnits().equals(Constants.MMOL) ? Constants.defaultActivityTTmmol : Constants.defaultActivityTTmgdl);
activityTT = activityTT > 0 ? activityTT : currentProfile.getUnits().equals(Constants.MMOL) ? Constants.defaultActivityTTmmol : Constants.defaultActivityTTmgdl;
int eatingSoonTTDuration = SP.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration);
eatingSoonTTDuration = eatingSoonTTDuration > 0 ? eatingSoonTTDuration : Constants.defaultEatingSoonTTDuration;
double eatingSoonTT = SP.getDouble(R.string.key_eatingsoon_target, currentProfile.getUnits().equals(Constants.MMOL) ? Constants.defaultEatingSoonTTmmol : Constants.defaultEatingSoonTTmgdl);
eatingSoonTT = eatingSoonTT > 0 ? eatingSoonTT : currentProfile.getUnits().equals(Constants.MMOL) ? Constants.defaultEatingSoonTTmmol : Constants.defaultEatingSoonTTmgdl;
if (startActivityTTCheckbox.isChecked()) {
if (currentProfile.getUnits().equals(Constants.MMOL)) {
confirmMessage += "<br/>" + MainApp.gs(R.string.temptargetshort) + ": " + "<font color='" + MainApp.gc(R.color.high) + "'>" + DecimalFormatter.to1Decimal(activityTT) + " mmol/l (" + ((int) activityTTDuration) + " min)</font>";
} else
confirmMessage += "<br/>" + MainApp.gs(R.string.temptargetshort) + ": " + "<font color='" + MainApp.gc(R.color.high) + "'>" + DecimalFormatter.to0Decimal(activityTT) + " mg/dl (" + ((int) activityTTDuration) + " min)</font>";
}
if (startEatingSoonTTCheckbox.isChecked() && !startActivityTTCheckbox.isChecked()) {
if (currentProfile.getUnits().equals(Constants.MMOL)) {
confirmMessage += "<br/>" + MainApp.gs(R.string.temptargetshort) + ": " + "<font color='" + MainApp.gc(R.color.high) + "'>" + DecimalFormatter.to1Decimal(eatingSoonTT) + " mmol/l (" + eatingSoonTTDuration + " min)</font>";
} else
confirmMessage += "<br/>" + MainApp.gs(R.string.temptargetshort) + ": " + "<font color='" + MainApp.gc(R.color.high) + "'>" + DecimalFormatter.to0Decimal(eatingSoonTT) + " mg/dl (" + eatingSoonTTDuration + " min)</font>";
}
final double finalActivityTT = activityTT;
final double finalEatigSoonTT = eatingSoonTT;
final int finalActivityTTDuration = activityTTDuration;
final int finalEatingSoonTTDuration = eatingSoonTTDuration;
if (StringUtils.isNoneEmpty(food)) {
confirmMessage += "<br/>" + "Food: " + food;
}
if (!initialEventTime.equals(eventTime)) {
confirmMessage += "<br/> Time: " + DateUtil.dateAndTimeString(eventTime);
}
if (confirmMessage.length() > 0) {
final int finalCarbsAfterConstraints = carbsAfterConstraints;
final Context context = getContext();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.gs(R.string.confirmation));
if (confirmMessage.startsWith("<br/>"))
confirmMessage = confirmMessage.substring("<br/>".length());
builder.setMessage(Html.fromHtml(confirmMessage));
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
synchronized (builder) {
if (accepted) {
log.debug("guarding: already accepted");
return;
}
accepted = true;
if (suspendLoopCheckbox.isChecked()) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
activeloop.suspendTo(System.currentTimeMillis() + 30L * 60 * 1000);
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
}
if (startActivityTTCheckbox.isChecked()) {
TempTarget tempTarget = new TempTarget();
tempTarget.date = System.currentTimeMillis();
tempTarget.durationInMinutes = finalActivityTTDuration;
tempTarget.reason = MainApp.gs(R.string.activity);
tempTarget.source = Source.USER;
tempTarget.low = Profile.toMgdl(finalActivityTT, currentProfile.getUnits());
tempTarget.high = Profile.toMgdl(finalActivityTT, currentProfile.getUnits());
MainApp.getDbHelper().createOrUpdate(tempTarget);
} else if (startEatingSoonTTCheckbox.isChecked()) {
TempTarget tempTarget = new TempTarget();
tempTarget.date = System.currentTimeMillis();
tempTarget.durationInMinutes = finalEatingSoonTTDuration;
tempTarget.reason = MainApp.gs(R.string.eatingsoon);
tempTarget.source = Source.USER;
tempTarget.low = Profile.toMgdl(finalEatigSoonTT, currentProfile.getUnits());
tempTarget.high = Profile.toMgdl(finalEatigSoonTT, currentProfile.getUnits());
MainApp.getDbHelper().createOrUpdate(tempTarget);
}
if (finalCarbsAfterConstraints > 0 || food != null) {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.date = eventTime.getTime();
detailedBolusInfo.eventType = CareportalEvent.CARBCORRECTION;
detailedBolusInfo.carbs = finalCarbsAfterConstraints;
// detailedBolusInfo.food = food;
detailedBolusInfo.context = context;
detailedBolusInfo.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
}
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
dismiss();
} else
dismiss();
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
eventTime.setYear(year - 1900);
eventTime.setMonth(monthOfYear);
eventTime.setDate(dayOfMonth);
dateButton.setText(DateUtil.dateString(eventTime));
}
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
eventTime.setHours(hourOfDay);
eventTime.setMinutes(minute);
eventTime.setSeconds(second);
timeButton.setText(DateUtil.timeString(eventTime));
}
}
|
package ninja.joshdavis;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* Launcher for the graphical interface
*
*/
public class Remoniker {
private static void createAndShowGUI() {
AppFrame frame = new AppFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640,480);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
|
package it_minds.dk.eindberetningmobil_android.constants;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class DistanceDisplayer {
private static DecimalFormat decimalFormat = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US));
/**
* Converts the distance in meters to km prettified string.
* @param distance the distance in meters
* @return Prettified String to be shown to the user
*/
public static String formatDistance(double distance) {
return decimalFormat.format(distance / 1000.0d).replace('.', ',');//danish style
}
/**
* Converts the distance in meters to a string (With format "X.X") for upload to database
* (Needs to be '.' seperator for database)
* @param distance the distance in meters
* @return A string representing the distance in km, usable for database upload
*/
public static String formatDisanceForUpload(double distance){
return decimalFormat.format(distance / 1000.0d);//english style (With '.' as seperator)
}
/**
* Converts the accuracy in meters to a comma separated string
* @param acc The accuracy in meters
* @return Prettified string to shown to the user
*/
public static String formatAccuracy(double acc){
return decimalFormat.format(acc).replace('.', ',');//danish style
}
}
|
package org.cojen.tupl;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import static org.cojen.tupl.DirectPageOps.*;
import static org.cojen.tupl.Utils.*;
/**
* Core _TreeCursor ValueAccessor implementation.
*
* @author Generated by PageAccessTransformer from TreeValue.java
*/
final class _TreeValue {
// Op ordinals are relevant.
static final int OP_LENGTH = 0, OP_READ = 1, OP_SET_LENGTH = 2, OP_WRITE = 3;
// Touches a fragment without extending the value length. Used for file compaction.
static final byte[] TOUCH_VALUE = new byte[0];
private _TreeValue() {}
/**
* Determine if any fragment nodes at the given position are outside the compaction zone.
*
* @param frame latched leaf, not split, never released by this method
* @param highestNodeId defines the highest node before the compaction zone; anything
* higher is in the compaction zone
* @return -1 if position is too high, 0 if no compaction required, or 1 if any nodes are
* in the compaction zone
*/
static int compactCheck(final _CursorFrame frame, long pos, final long highestNodeId)
throws IOException
{
final _Node node = frame.mNode;
int nodePos = frame.mNodePos;
if (nodePos < 0) {
// Value doesn't exist.
return -1;
}
final long page = node.mPage;
int loc = p_ushortGetLE(page, node.searchVecStart() + nodePos);
// Skip the key.
loc += _Node.keyLengthAtLoc(page, loc);
int vHeader = p_byteGet(page, loc++);
if (vHeader >= 0) {
// Not fragmented.
return pos >= vHeader ? -1 : 0;
}
int len;
if ((vHeader & 0x20) == 0) {
len = 1 + (((vHeader & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (vHeader != -1) {
len = 1 + (((vHeader & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
return -1;
}
if ((vHeader & _Node.ENTRY_FRAGMENTED) == 0) {
// Not fragmented.
return pos >= len ? -1 : 0;
}
// Read the fragment header, as described by the _LocalDatabase.fragment method.
final int fHeader = p_byteGet(page, loc++);
final long fLen = _LocalDatabase.decodeFullFragmentedValueLength(fHeader, page, loc);
if (pos >= fLen) {
return -1;
}
loc = skipFragmentedLengthField(loc, fHeader);
if ((fHeader & 0x02) != 0) {
// Inline content.
final int fInlineLen = p_ushortGetLE(page, loc);
if (pos < fInlineLen) {
// Positioned within inline content.
return 0;
}
pos -= fInlineLen;
loc = loc + 2 + fInlineLen;
}
_LocalDatabase db = node.getDatabase();
if ((fHeader & 0x01) == 0) {
// Direct pointers.
loc += (((int) pos) / pageSize(db, page)) * 6;
final long fNodeId = p_uint48GetLE(page, loc);
return fNodeId > highestNodeId ? 1 : 0;
}
// Indirect pointers.
final long inodeId = p_uint48GetLE(page, loc);
if (inodeId == 0) {
// Sparse value.
return 0;
}
_Node inode = db.nodeMapLoadFragment(inodeId);
int level = db.calculateInodeLevels(fLen);
while (true) {
level
long levelCap = db.levelCap(level);
long childNodeId = p_uint48GetLE(inode.mPage, ((int) (pos / levelCap)) * 6);
inode.releaseShared();
if (childNodeId > highestNodeId) {
return 1;
}
if (level <= 0 || childNodeId == 0) {
return 0;
}
inode = db.nodeMapLoadFragment(childNodeId);
pos %= levelCap;
}
}
/**
* Caller must hold shared commit lock when using OP_SET_LENGTH or OP_WRITE.
*
* @param frame latched shared for read op, exclusive for write op; released only if an
* exception is thrown
* @param b ignored by OP_LENGTH; OP_SET_LENGTH must pass EMPTY_BYTES
* @return applicable only to OP_LENGTH and OP_READ
*/
@SuppressWarnings("fallthrough")
static long action(_TreeCursor cursor, _CursorFrame frame, int op,
long pos, byte[] b, int bOff, int bLen)
throws IOException
{
while (true) {
_Node node = frame.mNode;
int nodePos = frame.mNodePos;
if (nodePos < 0) {
// Value doesn't exist.
if (op <= OP_READ) {
// Handle OP_LENGTH and OP_READ.
return -1;
}
// Handle OP_SET_LENGTH and OP_WRITE.
if (b == TOUCH_VALUE) {
return 0;
}
// Method releases latch if an exception is thrown.
node = cursor.insertBlank(frame, node, pos + bLen);
if (bLen <= 0) {
return 0;
}
// Fallthrough and complete the write operation. Need to re-assign nodePos,
// because the insert operation changed it.
nodePos = frame.mNodePos;
}
long page = node.mPage;
int loc = p_ushortGetLE(page, node.searchVecStart() + nodePos);
final int kHeaderLoc = loc;
// Skip the key.
loc += _Node.keyLengthAtLoc(page, loc);
final int vHeaderLoc = loc; // location of raw value header
final int vLen; // length of raw value sans header
nonFrag: {
final int vHeader = p_byteGet(page, loc++); // header byte of raw value
decodeLen: if (vHeader >= 0) {
vLen = vHeader;
} else {
if ((vHeader & 0x20) == 0) {
vLen = 1 + (((vHeader & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (vHeader != -1) {
vLen = 1 + (((vHeader & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
if (op <= OP_READ) {
// Handle OP_LENGTH and OP_READ.
return -1;
}
if (b == TOUCH_VALUE) {
return 0;
}
// Replace the ghost with an empty value.
p_bytePut(page, vHeaderLoc, 0);
vLen = 0;
break decodeLen;
}
if ((vHeader & _Node.ENTRY_FRAGMENTED) != 0) {
// Value is fragmented.
break nonFrag;
}
}
// Operate against a non-fragmented value.
switch (op) {
case OP_LENGTH: default:
return vLen;
case OP_READ:
if (bLen <= 0 || pos >= vLen) {
bLen = 0;
} else {
bLen = Math.min((int) (vLen - pos), bLen);
p_copyToArray(page, (int) (loc + pos), b, bOff, bLen);
}
return bLen;
case OP_SET_LENGTH:
if (pos <= vLen) {
// Truncate length.
int newLen = (int) pos;
int oldLen = (int) vLen;
int garbageAccum = oldLen - newLen;
shift: {
final int vLoc;
final int vShift;
if (newLen <= 127) {
p_bytePut(page, vHeaderLoc, newLen);
if (oldLen <= 127) {
break shift;
} else if (oldLen <= 8192) {
vLoc = vHeaderLoc + 2;
vShift = 1;
} else {
vLoc = vHeaderLoc + 3;
vShift = 2;
}
} else if (newLen <= 8192) {
p_bytePut(page, vHeaderLoc, 0x80 | ((newLen - 1) >> 8));
p_bytePut(page, vHeaderLoc + 1, newLen - 1);
if (oldLen <= 8192) {
break shift;
} else {
vLoc = vHeaderLoc + 3;
vShift = 1;
}
} else {
p_bytePut(page, vHeaderLoc, 0xa0 | ((newLen - 1) >> 16));
p_bytePut(page, vHeaderLoc + 1, (newLen - 1) >> 8);
p_bytePut(page, vHeaderLoc + 2, newLen - 1);
break shift;
}
garbageAccum += vShift;
p_copy(page, vLoc, page, vLoc - vShift, newLen);
}
node.garbage(node.garbage() + garbageAccum);
return 0;
}
// Break out for length increase, by appending an empty value.
break;
case OP_WRITE:
if (b == TOUCH_VALUE) {
return 0;
}
if (pos < vLen) {
final long end = pos + bLen;
if (end <= vLen) {
// Writing within existing value region.
p_copyFromArray(b, bOff, page, (int) (loc + pos), bLen);
return 0;
} else if (pos == 0 && bOff == 0 && bLen == b.length) {
// Writing over the entire value.
try {
node.updateLeafValue(frame, cursor.mTree, nodePos, 0, b);
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
return 0;
} else {
// Write the overlapping region, and then append the rest.
int len = (int) (vLen - pos);
p_copyFromArray(b, bOff, page, (int) (loc + pos), len);
pos = vLen;
bOff += len;
bLen -= len;
}
}
// Break out for append.
break;
}
// This point is reached for appending to a non-fragmented value. There's all
// kinds of optimizations that can be performed here, but keep things
// simple. Delete the old value, insert a blank value, and then update it.
byte[] oldValue = new byte[vLen];
p_copyToArray(page, loc, oldValue, 0, oldValue.length);
node.deleteLeafEntry(nodePos);
frame.mNodePos = ~nodePos;
// Method releases latch if an exception is thrown.
cursor.insertBlank(frame, node, pos + bLen);
op = OP_WRITE;
if (bLen <= 0) {
pos = 0;
b = oldValue;
bOff = 0;
bLen = oldValue.length;
} else {
action(cursor, frame, OP_WRITE, 0, oldValue, 0, oldValue.length);
}
continue;
}
// Operate against a fragmented value. First read the fragment header, as described
// by the _LocalDatabase.fragment method.
int fHeaderLoc; // location of fragmented value header
int fHeader; // header byte of fragmented value
long fLen; // length of fragmented value (when fully reconstructed)
fHeaderLoc = loc;
fHeader = p_byteGet(page, loc++);
switch ((fHeader >> 2) & 0x03) {
default:
fLen = p_ushortGetLE(page, loc);
break;
case 1:
fLen = p_intGetLE(page, loc) & 0xffffffffL;
break;
case 2:
fLen = p_uint48GetLE(page, loc);
break;
case 3:
fLen = p_longGetLE(page, loc);
if (fLen < 0) {
node.release(op > OP_READ);
throw new LargeValueException(fLen);
}
break;
}
loc = skipFragmentedLengthField(loc, fHeader);
switch (op) {
case OP_LENGTH: default:
return fLen;
case OP_READ: try {
if (bLen <= 0 || pos >= fLen) {
return 0;
}
bLen = (int) Math.min(fLen - pos, bLen);
final int total = bLen;
if ((fHeader & 0x02) != 0) {
// Inline content.
final int fInlineLen = p_ushortGetLE(page, loc);
loc += 2;
final int amt = (int) (fInlineLen - pos);
if (amt <= 0) {
// Not reading any inline content.
pos -= fInlineLen;
} else if (bLen <= amt) {
p_copyToArray(page, (int) (loc + pos), b, bOff, bLen);
return bLen;
} else {
p_copyToArray(page, (int) (loc + pos), b, bOff, amt);
bLen -= amt;
bOff += amt;
pos = 0;
}
loc += fInlineLen;
}
final _LocalDatabase db = node.getDatabase();
if ((fHeader & 0x01) == 0) {
// Direct pointers.
final int ipos = (int) pos;
final int pageSize = pageSize(db, page);
loc += (ipos / pageSize) * 6;
int fNodeOff = ipos % pageSize;
while (true) {
final int amt = Math.min(bLen, pageSize - fNodeOff);
final long fNodeId = p_uint48GetLE(page, loc);
if (fNodeId == 0) {
// Reading a sparse value.
Arrays.fill(b, bOff, bOff + amt, (byte) 0);
} else {
final _Node fNode = db.nodeMapLoadFragment(fNodeId);
p_copyToArray(fNode.mPage, fNodeOff, b, bOff, amt);
fNode.releaseShared();
}
bLen -= amt;
if (bLen <= 0) {
return total;
}
bOff += amt;
loc += 6;
fNodeOff = 0;
}
}
// Indirect pointers.
final long inodeId = p_uint48GetLE(page, loc);
if (inodeId == 0) {
// Reading a sparse value.
Arrays.fill(b, bOff, bOff + bLen, (byte) 0);
} else {
final _Node inode = db.nodeMapLoadFragment(inodeId);
final int levels = db.calculateInodeLevels(fLen);
try {
readMultilevelFragments(db, pos, levels, inode, b, bOff, bLen);
} finally {
inode.releaseShared();
}
}
return total;
} catch (Throwable e) {
node.releaseShared();
throw e;
}
case OP_SET_LENGTH:
long endPos = pos + bLen;
if (endPos <= fLen) {
if (endPos == fLen) {
return 0;
}
// Truncate fragmented value.
int fInlineLoc = loc;
int fInlineLen = 0;
if ((fHeader & 0x02) != 0) {
// Inline content.
fInlineLen = p_ushortGetLE(page, loc);
fInlineLoc = loc + 2;
loc = fInlineLoc + fInlineLen;
}
_LocalDatabase db = node.getDatabase();
doTruncate: if ((fHeader & 0x01) == 0) {
// Truncate direct pointers.
int pageSize = pageSize(db, page);
int oldCount = (int) pointerCount(pageSize, fLen - fInlineLen);
int newCount = (int) pointerCount(pageSize, endPos - fInlineLen);
int lowLoc = loc + 6 * newCount;
long remainder = (endPos - fInlineLen) % pageSize;
_Node lastNode = null;
// FIXME: truncate in forward order, for simplicity and consistency
if (remainder > 0) {
// The last highest remaining page (at lowLoc) will need to be
// zero-filled up to the end. Attempt to dirty it early, in case an
// exception is thrown.
long lastNodeId = p_uint48GetLE(page, lowLoc - 6);
if (lastNodeId != 0) {
lastNode = db.nodeMapLoadFragmentExclusive(lastNodeId, true);
try {
if (db.markFragmentDirty(lastNode)) {
p_int48PutLE(page, lowLoc - 6, lastNode.mId);
}
} catch (Throwable e) {
lastNode.releaseExclusive();
throw e;
}
}
}
if (newCount < oldCount) {
int highLoc = loc + 6 * oldCount;
int shrinkage = highLoc - lowLoc;
do {
highLoc -= 6;
long nodeId = p_uint48GetLE(page, highLoc);
try {
db.deleteFragment(nodeId);
} catch (Throwable e) {
// Handle partial truncation.
if (lastNode != null) {
lastNode.releaseExclusive();
}
highLoc += 6;
shrinkage -= highLoc - lowLoc;
if (shrinkage > 0) {
long remainingLen = fInlineLen
+ ((highLoc - lowLoc) / 6L) * pageSize;
fHeaderLoc = truncateFragmented
(node, page, vHeaderLoc, vLen, shrinkage);
updateLengthField(page, fHeaderLoc, remainingLen);
}
throw e;
}
} while (highLoc > lowLoc);
if (lowLoc == loc) {
// All pointers are gone, so convert to a normal value.
int newLen = (int) endPos;
fragmentedToNormal(node, page, vHeaderLoc, fInlineLoc, newLen,
shrinkage + (fInlineLen - newLen));
return 0;
}
fHeaderLoc = truncateFragmented
(node, page, vHeaderLoc, vLen, shrinkage);
}
if (lastNode != null) {
// Zero fill the end.
p_clear(lastNode.mPage, (int) remainder, pageSize);
lastNode.releaseExclusive();
}
} else {
// Truncate indirect pointers.
long inodeId = p_uint48GetLE(page, loc);
if (inodeId == 0) {
break doTruncate;
}
try {
_Node inode = db.nodeMapLoadFragmentExclusive(inodeId, true);
int levels;
try {
if (db.markFragmentDirty(inode)) {
p_int48PutLE(page, loc, inode.mId);
}
levels = db.calculateInodeLevels(fLen);
truncateMultilevelFragments
(db, endPos, levels, inode, fLen - endPos);
} catch (Throwable e) {
inode.releaseExclusive();
throw e;
}
final int newLevels = db.calculateInodeLevels(endPos);
if (newLevels >= levels) {
inode.releaseExclusive();
break doTruncate;
}
do {
long childNodeId = p_uint48GetLE(inode.mPage, 0);
if (childNodeId == 0) {
inodeId = 0;
break;
}
_Node childNode;
try {
childNode = db.nodeMapLoadFragmentExclusive(childNodeId, true);
} catch (Throwable e) {
inode.releaseExclusive();
// Panic.
db.close(e);
throw e;
}
db.deleteNode(inode);
inode = childNode;
inodeId = inode.mId;
} while (--levels > newLevels);
p_int48PutLE(page, loc, inodeId);
if (newLevels <= 0) {
if (endPos == 0) {
// Convert to an empty value.
p_bytePut(page, vHeaderLoc, 0);
int garbageAccum = fHeaderLoc - vHeaderLoc + vLen - 1;
node.garbage(node.garbage() + garbageAccum);
db.deleteNode(inode);
break doTruncate;
}
// Convert to direct pointer format.
p_bytePut(page, fHeaderLoc, fHeader & ~0x01);
}
inode.releaseExclusive();
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
}
updateLengthField(page, fHeaderLoc, endPos);
return 0;
}
// Fall through to extend the length.
case OP_WRITE:
endPos = pos + bLen;
int fInlineLen = 0;
if ((fHeader & 0x02) != 0) {
// Inline content.
fInlineLen = p_ushortGetLE(page, loc);
loc += 2;
final long amt = fInlineLen - pos;
if (amt > 0) {
if (bLen <= amt) {
// Only writing inline content.
p_copyFromArray(b, bOff, page, (int) (loc + pos), bLen);
return 0;
}
// Write just the inline region, and then never touch it again if
// continued to the outermost loop.
p_copyFromArray(b, bOff, page, (int) (loc + pos), (int) amt);
bLen -= amt;
bOff += amt;
pos = fInlineLen;
}
// Move location to first page pointer.
loc += fInlineLen;
}
final _LocalDatabase db;
final int pageSize;
if (endPos <= fLen) {
// Value doesn't need to be extended.
if (bLen == 0 && b != TOUCH_VALUE) {
return 0;
}
db = node.getDatabase();
if ((fHeader & 0x01) != 0) try {
// Indirect pointers.
pos -= fInlineLen; // safe to update now that outermost loop won't continue
fLen -= fInlineLen;
final _Node inode = prepareMultilevelWrite(db, page, loc);
try {
final int levels = db.calculateInodeLevels(fLen);
writeMultilevelFragments(db, pos, levels, inode, b, bOff, bLen);
} finally {
inode.releaseExclusive();
}
return 0;
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
pageSize = pageSize(db, page);
} else {
if (b == TOUCH_VALUE) {
// Don't extend the value.
return 0;
}
// Extend the value.
int fieldGrowth = lengthFieldGrowth(fHeader, endPos);
if (fieldGrowth > 0) {
tryIncreaseLengthField(cursor, frame, kHeaderLoc, vHeaderLoc, vLen,
fHeaderLoc, fieldGrowth);
continue;
}
db = node.getDatabase();
if ((fHeader & 0x01) != 0) try {
// Extend the value with indirect pointers.
pos -= fInlineLen; // safe to update now that outermost loop won't continue
_Node inode = prepareMultilevelWrite(db, page, loc);
// Levels required before extending...
int levels = db.calculateInodeLevels(fLen - fInlineLen);
// Compare to new full indirect length.
long newLen = endPos - fInlineLen;
if (db.levelCap(levels) < newLen) {
// Need to add more inode levels.
int newLevels = db.calculateInodeLevels(newLen);
if (newLevels <= levels) {
throw new AssertionError();
}
pageSize = pageSize(db, page);
_Node[] newNodes = new _Node[newLevels - levels];
for (int i=0; i<newNodes.length; i++) {
try {
newNodes[i] = db.allocDirtyFragmentNode();
} catch (Throwable e) {
try {
// Clean up the mess.
while (--i >= 0) {
db.deleteNode(newNodes[i], true);
}
} catch (Throwable e2) {
suppress(e, e2);
db.close(e);
}
throw e;
}
}
for (_Node upper : newNodes) {
long upage = upper.mPage;
p_int48PutLE(upage, 0, inode.mId);
inode.releaseExclusive();
// Zero-fill the rest.
p_clear(upage, 6, pageSize);
inode = upper;
}
levels = newLevels;
p_int48PutLE(page, loc, inode.mId);
}
updateLengthField(page, fHeaderLoc, endPos);
try {
writeMultilevelFragments(db, pos, levels, inode, b, bOff, bLen);
} finally {
inode.releaseExclusive();
}
return 0;
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
// Extend the value with direct pointers.
pageSize = pageSize(db, page);
long ptrGrowth = pointerCount(pageSize, endPos - fInlineLen)
- pointerCount(pageSize, fLen - fInlineLen);
if (ptrGrowth > 0) {
int newLoc = tryExtendDirect(cursor, frame, kHeaderLoc, vHeaderLoc, vLen,
fHeaderLoc, ptrGrowth * 6);
// Note: vHeaderLoc is now wrong and cannot be used.
if (newLoc < 0) {
// Format conversion or latch re-acquisition.
continue;
}
// Page reference might have changed.
page = node.mPage;
// Fix broken location variables that are still required.
int delta = newLoc - fHeaderLoc;
loc += delta;
fHeaderLoc = newLoc;
}
updateLengthField(page, fHeaderLoc, endPos);
}
// Direct pointers.
pos -= fInlineLen; // safe to update now that outermost loop won't continue
final int ipos = (int) pos;
loc += (ipos / pageSize) * 6;
int fNodeOff = ipos % pageSize;
while (true) try {
final int amt = Math.min(bLen, pageSize - fNodeOff);
final long fNodeId = p_uint48GetLE(page, loc);
if (fNodeId == 0) {
if (amt > 0) {
// Writing into a sparse value. Allocate a node and point to it.
final _Node fNode = db.allocDirtyFragmentNode();
try {
p_int48PutLE(page, loc, fNode.mId);
// Now write to the new page, zero-filling the gaps.
long fNodePage = fNode.mPage;
p_clear(fNodePage, 0, fNodeOff);
p_copyFromArray(b, bOff, fNodePage, fNodeOff, amt);
p_clear(fNodePage, fNodeOff + amt, pageSize);
} finally {
fNode.releaseExclusive();
}
}
} else {
if (amt > 0 || b == TOUCH_VALUE) {
// Obtain node from cache, or read it only for partial write.
final _Node fNode = db
.nodeMapLoadFragmentExclusive(fNodeId, amt < pageSize);
try {
if (db.markFragmentDirty(fNode)) {
p_int48PutLE(page, loc, fNode.mId);
}
p_copyFromArray(b, bOff, fNode.mPage, fNodeOff, amt);
} finally {
fNode.releaseExclusive();
}
}
}
bLen -= amt;
if (bLen <= 0) {
return 0;
}
bOff += amt;
loc += 6;
fNodeOff = 0;
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
} // end switch(op)
}
}
/**
* @param pos value position being read
* @param level inode level; at least 1
* @param inode shared latched parent inode; never released by this method
* @param b slice of complete value being reconstructed
* @param bLen must be more than zero
*/
private static void readMultilevelFragments(final _LocalDatabase db,
final long pos, int level, final _Node inode,
final byte[] b, int bOff, int bLen)
throws IOException
{
long page = inode.mPage;
level
long levelCap = db.levelCap(level);
int poffset = ((int) (pos / levelCap)) * 6;
// Handle a possible partial read from the first page.
long ppos = pos % levelCap;
while (true) {
long childNodeId = p_uint48GetLE(page, poffset);
int len = (int) Math.min(levelCap - ppos, bLen);
if (childNodeId == 0) {
// Reading a sparse value.
Arrays.fill(b, bOff, bOff + len, (byte) 0);
} else {
_Node childNode = db.nodeMapLoadFragment(childNodeId);
try {
if (level <= 0) {
p_copyToArray(childNode.mPage, (int) ppos, b, bOff, len);
} else {
readMultilevelFragments(db, ppos, level, childNode, b, bOff, len);
}
} finally {
childNode.releaseShared();
}
}
bLen -= len;
if (bLen <= 0) {
break;
}
bOff += len;
poffset += 6;
// Remaining reads begin at the start of the page.
ppos = 0;
}
}
/**
* @param loc location of root inode in the page
* @return dirtied root inode with exclusive latch held
*/
private static _Node prepareMultilevelWrite(_LocalDatabase db, long page, int loc)
throws IOException
{
final _Node inode;
final long inodeId = p_uint48GetLE(page, loc);
if (inodeId == 0) {
// Writing into a sparse value. Allocate a node and point to it.
inode = db.allocDirtyFragmentNode();
p_clear(inode.mPage, 0, pageSize(db, inode.mPage));
} else {
inode = db.nodeMapLoadFragmentExclusive(inodeId, true);
try {
if (!db.markFragmentDirty(inode)) {
// Already dirty, so no need to update the pointer.
return inode;
}
} catch (Throwable e) {
inode.releaseExclusive();
throw e;
}
}
p_int48PutLE(page, loc, inode.mId);
return inode;
}
/**
* @param pos value position being written
* @param level inode level; at least 1
* @param inode exclusively latched parent inode; never released by this method
* @param b slice of complete value being written
* @param bLen can be zero
*/
private static void writeMultilevelFragments(final _LocalDatabase db,
final long pos, int level, final _Node inode,
final byte[] b, int bOff, int bLen)
throws IOException
{
long page = inode.mPage;
level
long levelCap = db.levelCap(level);
int poffset = ((int) (pos / levelCap)) * 6;
// Handle a possible partial write to the first page.
long ppos = pos % levelCap;
final int pageSize = pageSize(db, page);
while (true) {
int len = (int) Math.min(levelCap - ppos, bLen);
int off = (int) ppos;
final _Node childNode;
setPtr: {
long childNodeId = p_uint48GetLE(page, poffset);
boolean partial = level > 0 | off > 0 | len < pageSize;
if (childNodeId == 0) {
// Writing into a sparse value. Allocate a node and point to it.
childNode = db.allocDirtyFragmentNode();
if (partial) {
// New page must be zero-filled.
p_clear(childNode.mPage, 0, pageSize);
}
} else {
// Obtain node from cache, or read it only for partial write.
childNode = db.nodeMapLoadFragmentExclusive(childNodeId, partial);
try {
if (!db.markFragmentDirty(childNode)) {
// Already dirty, so no need to update the pointer.
break setPtr;
}
} catch (Throwable e) {
childNode.releaseExclusive();
throw e;
}
}
p_int48PutLE(page, poffset, childNode.mId);
}
try {
if (level <= 0) {
p_copyFromArray(b, bOff, childNode.mPage, off, len);
} else {
writeMultilevelFragments(db, ppos, level, childNode, b, bOff, len);
}
} finally {
childNode.releaseExclusive();
}
bLen -= len;
if (bLen <= 0) {
break;
}
bOff += len;
poffset += 6;
// Remaining writes begin at the start of the page.
ppos = 0;
}
}
/**
* @param pos value position being truncated
* @param level inode level; at least 1
* @param inode exclusively latched parent inode; never released by this method
* @param truncateLen full truncation length (to the end)
*/
private static void truncateMultilevelFragments(final _LocalDatabase db,
final long pos, int level, final _Node inode,
long truncateLen)
throws IOException
{
long page = inode.mPage;
level
long levelCap = db.levelCap(level);
int poffset = ((int) (pos / levelCap)) * 6;
// Handle a possible partial truncation of the first page.
long ppos = pos % levelCap;
while (true) {
long len = Math.min(levelCap - ppos, truncateLen);
long childNodeId = p_uint48GetLE(page, poffset);
if (childNodeId != 0) {
if (ppos <= 0 || len >= levelCap) {
// Full truncation of inode.
if (level <= 0) {
db.deleteFragment(childNodeId);
} else {
_Node childNode = db.nodeMapLoadFragmentExclusive(childNodeId, true);
try {
truncateMultilevelFragments(db, ppos, level, childNode, len);
} catch (Throwable e) {
childNode.releaseExclusive();
throw e;
}
db.deleteNode(childNode);
}
p_int48PutLE(page, poffset, 0);
} else {
// Partial truncation of inode.
_Node childNode = db.nodeMapLoadFragmentExclusive(childNodeId, true);
try {
if (db.markFragmentDirty(childNode)) {
p_int48PutLE(page, poffset, childNode.mId);
}
if (level <= 0) {
p_clear(childNode.mPage, (int) ppos, (int) levelCap);
} else {
truncateMultilevelFragments(db, ppos, level, childNode, len);
}
} finally {
childNode.releaseExclusive();
}
}
}
truncateLen -= len;
if (truncateLen <= 0) {
break;
}
poffset += 6;
// Remaining truncates begin at the start of the page.
ppos = 0;
}
}
/**
* Returns the amount of bytes which must be added to the length field for the given
* length.
*
* @param fHeader header byte of fragmented value
* @param fLen new fragmented value length
* @return 0, 2, 4, or 6
*/
private static int lengthFieldGrowth(int fHeader, long fLen) {
int growth = 0;
switch ((fHeader >> 2) & 0x03) {
case 0: // (2 byte length field)
if (fLen < (1L << (2 * 8))) {
break;
}
growth = 2;
case 1: // (4 byte length field)
if (fLen < (1L << (4 * 8))) {
break;
}
growth += 2;
case 2: // (6 byte length field)
if (fLen < (1L << (6 * 8))) {
break;
}
growth += 2;
}
return growth;
}
/**
* Updates the fragmented value length, blindly assuming that the field is large enough.
*
* @param fHeaderLoc location of fragmented value header
* @param fLen new fragmented value length
*/
private static void updateLengthField(long page, int fHeaderLoc, long fLen) {
int fHeader = p_byteGet(page, fHeaderLoc);
switch ((fHeader >> 2) & 0x03) {
case 0: // (2 byte length field)
p_shortPutLE(page, fHeaderLoc + 1, (int) fLen);
break;
case 1: // (4 byte length field)
p_intPutLE(page, fHeaderLoc + 1, (int) fLen);
break;
case 2: // (6 byte length field)
p_int48PutLE(page, fHeaderLoc + 1, fLen);
break;
default: // (8 byte length field)
p_longPutLE(page, fHeaderLoc + 1, fLen);
break;
}
}
/**
* Attempt to increase the size of the fragmented length field, for supporting larger
* sizes. If not enough space exists to increase the size, the value format is converted
* and the field size doesn't change.
*
* As a side effect of calling this method, the page referenced by the node can change when
* a non-negative value is returned. Also, any locations within the page may changed.
* Caller should always continue from the beginning after calling this method.
*
* The node latch is released if an exception is thrown.
*
* @param frame latched exclusive and dirtied
* @param kHeaderLoc location of key header
* @param vHeaderLoc location of raw value header
* @param vLen length of raw value sans header
* @param fHeaderLoc location of fragmented value header
* @param growth amount of zero bytes to add to the length field (2, 4, or 6)
*/
private static int tryIncreaseLengthField(final _TreeCursor cursor, final _CursorFrame frame,
final int kHeaderLoc,
final int vHeaderLoc, final int vLen,
final int fHeaderLoc, final long growth)
throws IOException
{
final int fOffset = fHeaderLoc - kHeaderLoc;
final long newEntryLen = fOffset + vLen + growth;
final _Node node = frame.mNode;
if (newEntryLen > node.getDatabase().mMaxFragmentedEntrySize) {
compactDirectFormat(cursor, frame, kHeaderLoc, vHeaderLoc, vLen, fHeaderLoc);
return -1;
}
final _Tree tree = cursor.mTree;
try {
final int igrowth = (int) growth;
final byte[] newValue = new byte[vLen + igrowth];
final long page = node.mPage;
// Update the header with the new field size.
int fHeader = p_byteGet(page, fHeaderLoc);
newValue[0] = (byte) (fHeader + (igrowth << 1));
// Copy the length field.
int srcLoc = fHeaderLoc + 1;
int fieldLen = skipFragmentedLengthField(0, fHeader);
p_copyToArray(page, srcLoc, newValue, 1, fieldLen);
// Copy the rest.
srcLoc += fieldLen;
int dstLoc = 1 + fieldLen + igrowth;
p_copyToArray(page, srcLoc, newValue, dstLoc, newValue.length - dstLoc);
// Clear the fragmented bit so that the update method doesn't delete the pages.
p_bytePut(page, vHeaderLoc, p_byteGet(page, vHeaderLoc) & ~_Node.ENTRY_FRAGMENTED);
// The fragmented bit is set again by this call.
node.updateLeafValue(frame, tree, frame.mNodePos, _Node.ENTRY_FRAGMENTED, newValue);
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
if (node.mSplit != null) {
// Releases latch if an exception is thrown.
tree.finishSplit(frame, node);
// Finishing the split causes the node latch to be re-acquired, so start over.
return -2;
}
return 0;
}
private static long pointerCount(long pageSize, long len) {
long count = (len + pageSize - 1) / pageSize;
if (count < 0) {
count = pointerCountOverflow(pageSize, len);
}
return count;
}
private static long pointerCountOverflow(long pageSize, long len) {
return BigInteger.valueOf(len).add(BigInteger.valueOf(pageSize - 1))
.subtract(BigInteger.ONE).divide(BigInteger.valueOf(pageSize)).longValue();
}
/**
* Attempt to add bytes to a fragmented value which uses the direct format. If not enough
* space exists to add direct pointers, the value format is converted and no new pointers
* are added.
*
* As a side effect of calling this method, the page referenced by the node can change when
* a non-negative value is returned. Also, any locations within the page may changed.
* Specifically kHeaderLoc, vHeaderLoc, and fHeaderLoc. All will have moved by the same
* amount as fHeaderLoc.
*
* The node latch is released if an exception is thrown.
*
* @param frame latched exclusive and dirtied
* @param kHeaderLoc location of key header
* @param vHeaderLoc location of raw value header
* @param vLen length of raw value sans header
* @param fHeaderLoc location of fragmented value header
* @param growth amount of zero bytes to append
* @return updated fHeaderLoc, or negative if caller must continue from the beginning
* (caused by format conversion or latch re-acquisition)
*/
private static int tryExtendDirect(final _TreeCursor cursor, final _CursorFrame frame,
final int kHeaderLoc,
final int vHeaderLoc, final int vLen,
final int fHeaderLoc, final long growth)
throws IOException
{
final int fOffset = fHeaderLoc - kHeaderLoc;
final long newEntryLen = fOffset + vLen + growth;
final _Node node = frame.mNode;
if (newEntryLen > node.getDatabase().mMaxFragmentedEntrySize) {
compactDirectFormat(cursor, frame, kHeaderLoc, vHeaderLoc, vLen, fHeaderLoc);
return -1;
}
final _Tree tree = cursor.mTree;
try {
final byte[] newValue = new byte[vLen + (int) growth];
final long page = node.mPage;
p_copyToArray(page, fHeaderLoc, newValue, 0, vLen);
// Clear the fragmented bit so that the update method doesn't delete the pages.
p_bytePut(page, vHeaderLoc, p_byteGet(page, vHeaderLoc) & ~_Node.ENTRY_FRAGMENTED);
// The fragmented bit is set again by this call.
node.updateLeafValue(frame, tree, frame.mNodePos, _Node.ENTRY_FRAGMENTED, newValue);
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
if (node.mSplit != null) {
// Releases latch if an exception is thrown.
tree.finishSplit(frame, node);
// Finishing the split causes the node latch to be re-acquired, so start over.
return -2;
}
return p_ushortGetLE(node.mPage, node.searchVecStart() + frame.mNodePos) + fOffset;
}
/**
* @param loc location of fragmented length field
* @return location of inline content length field or first pointer
*/
private static int skipFragmentedLengthField(int loc, int fHeader) {
return loc + 2 + ((fHeader >> 1) & 0x06);
}
/**
* Compacts a fragmented value of direct pointers. Either its inline content is moved
* completely, or the value is converted to indirect format. Caller should always continue
* from the beginning after calling this method.
*
* The node latch is released if an exception is thrown.
*
* @param node latched exclusive and dirtied
* @param vHeaderLoc location of raw value header
* @param vLen length of raw value sans header
* @param fHeaderLoc location of fragmented value header
*/
private static void compactDirectFormat(final _TreeCursor cursor, final _CursorFrame frame,
final int kHeaderLoc,
final int vHeaderLoc, final int vLen,
final int fHeaderLoc)
throws IOException
{
final _Node node = frame.mNode;
final long page = node.mPage;
int loc = fHeaderLoc;
final int fHeader = p_byteGet(page, loc++);
final long fLen = _LocalDatabase.decodeFullFragmentedValueLength(fHeader, page, loc);
loc = skipFragmentedLengthField(loc, fHeader);
final int fInlineLen;
if ((fHeader & 0x02) == 0) {
fInlineLen = 0;
} else {
fInlineLen = p_ushortGetLE(page, loc);
loc = loc + 2 + fInlineLen;
}
// At this point, loc is at the first direct pointer.
final int tailLen = fHeaderLoc + vLen - loc; // length of all the direct pointers, in bytes
final _LocalDatabase db = node.getDatabase();
final int pageSize = pageSize(db, page);
final int shrinkage;
if (fInlineLen > 0) {
// Move all inline content into the fragment pages, and keep the direct format for
// now. This avoids pathological cases where so much inline content exists that
// converting to indirect format doesn't shrink the value. It also means that
// inline content should never exist when using the indirect format, because the
// initial store of a large value never creates inline content when indirect.
if (fInlineLen < 4) {
// Cannot add a new direct pointer, because there's no room for it in the
// current entry. So reconstruct the full value and update it.
byte[] newValue;
try {
byte[] fullValue = db.reconstruct(page, fHeaderLoc, vLen);
int max = db.mMaxFragmentedEntrySize - (vHeaderLoc - kHeaderLoc);
// Encode it this time without any inline content.
newValue = db.fragment(fullValue, fullValue.length, max, 0);
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
try {
node.updateLeafValue(frame, cursor.mTree, frame.mNodePos,
_Node.ENTRY_FRAGMENTED, newValue);
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
if (node.mSplit != null) {
// Releases latch if an exception is thrown.
cursor.mTree.finishSplit(frame, node);
}
return;
}
_Node leftNode;
_Node rightNode = null;
try {
if (pointerCount(pageSize, fLen) * 6 <= tailLen) {
// Highest node is underutilized (caused by an earlier truncation), and so
// a new node isn't required.
shrinkage = 2 + fInlineLen;
} else {
rightNode = db.allocDirtyFragmentNode();
p_clear(rightNode.mPage, fInlineLen, pageSize);
shrinkage = 2 + fInlineLen - 6;
}
leftNode = shiftDirectRight(db, page, loc, loc + tailLen, fInlineLen, rightNode);
} catch (Throwable e) {
node.releaseExclusive();
try {
// Clean up the mess.
if (rightNode != null) {
db.deleteNode(rightNode, true);
}
} catch (Throwable e2) {
suppress(e, e2);
db.close(e);
}
throw e;
}
// Move the inline content in place now that room has been made.
p_copy(page, loc - fInlineLen, leftNode.mPage, 0, fInlineLen);
leftNode.releaseExclusive();
// Shift page contents over inline content and inline length header.
p_copy(page, loc, page, loc - fInlineLen - 2, tailLen);
if (rightNode != null) {
// Reference the new node.
p_int48PutLE(page, loc - fInlineLen - 2 + tailLen, rightNode.mId);
}
// Clear the inline length field.
p_bytePut(page, fHeaderLoc, fHeader & ~0x02);
} else {
// Convert to indirect format.
if ((fLen - fInlineLen) > pageSize) {
_Node inode;
try {
inode = db.allocDirtyFragmentNode();
} catch (Throwable e) {
node.releaseExclusive();
throw e;
}
long ipage = inode.mPage;
p_copy(page, loc, ipage, 0, tailLen);
// Zero-fill the rest.
p_clear(ipage, tailLen, pageSize);
// Reference the root inode.
p_int48PutLE(page, loc, inode.mId);
inode.releaseExclusive();
}
// Switch to indirect format.
p_bytePut(page, fHeaderLoc, fHeader | 0x01);
shrinkage = tailLen - 6;
}
// Update the raw value length.
int newLen = vLen - shrinkage - 1; // minus one as required by field encoding
int header = p_byteGet(page, vHeaderLoc);
if ((header & 0x20) == 0) {
// Field length is 1..8192.
p_bytePut(page, vHeaderLoc, (header & 0xe0) | (newLen >> 8));
p_bytePut(page, vHeaderLoc + 1, newLen);
} else {
// Field length is 1..1048576.
p_bytePut(page, vHeaderLoc, (header & 0xf0) | (newLen >> 16));
p_bytePut(page, vHeaderLoc + 1, newLen >> 8);
p_bytePut(page, vHeaderLoc + 2, newLen);
}
// Update the garbage field.
node.garbage(node.garbage() + shrinkage);
if (node.shouldLeafMerge()) {
// Method always release the node latch, even if an exception is thrown.
cursor.mergeLeaf(frame, node);
frame.acquireExclusive();
}
}
/**
* Shift the entire contents of a direct-format fragmented value to the right.
*
* @param startLoc first direct pointer location
* @param endLoc last direct pointer location (exclusive)
* @param amount shift amount in bytes
* @param dstNode optional rightmost fragment node to shift into, latched exclusively
* @return leftmost fragment node, latched exclusively
*/
private static _Node shiftDirectRight(_LocalDatabase db, final long page,
int startLoc, int endLoc, int amount,
_Node dstNode)
throws IOException
{
// First make sure all the fragment nodes are dirtied, in case of an exception.
_Node[] fNodes = new _Node[(endLoc - startLoc) / 6];
try {
for (int i = 0, loc = startLoc; loc < endLoc; i++, loc += 6) {
_Node fNode = db.nodeMapLoadFragmentExclusive(p_uint48GetLE(page, loc), true);
fNodes[i] = fNode;
if (db.markFragmentDirty(fNode)) {
p_int48PutLE(page, loc, fNode.mId);
}
}
} catch (Throwable e) {
for (_Node fNode : fNodes) {
if (fNode != null) {
fNode.releaseExclusive();
}
}
throw e;
}
final int pageSize = pageSize(db, page);
for (int i = fNodes.length; --i >= 0; ) {
_Node fNode = fNodes[i];
long fPage = fNode.mPage;
if (dstNode != null) {
p_copy(fPage, pageSize - amount, dstNode.mPage, 0, amount);
dstNode.releaseExclusive();
}
p_copy(fPage, 0, fPage, amount, pageSize - amount);
dstNode = fNode;
}
return dstNode;
}
/**
* Convert a fragmented value which has no pointers into a normal non-fragmented value.
*
* @param fInlineLoc location of inline content
* @param fInlineLen length of inline content to keep (normal value length)
* @param shrinkage amount of bytes freed due to pointer deletion and inline reduction
*/
private static void fragmentedToNormal(final _Node node, final long page,
final int vHeaderLoc, final int fInlineLoc,
final int fInlineLen, final int shrinkage)
{
int loc = vHeaderLoc;
if (fInlineLen <= 127) {
p_bytePut(page, loc++, fInlineLen);
} else if (fInlineLen <= 8192) {
p_bytePut(page, loc++, 0x80 | ((fInlineLen - 1) >> 8));
p_bytePut(page, loc++, fInlineLen - 1);
} else {
p_bytePut(page, loc++, 0xa0 | ((fInlineLen - 1) >> 16));
p_bytePut(page, loc++, (fInlineLen - 1) >> 8);
p_bytePut(page, loc++, fInlineLen - 1);
}
p_copy(page, fInlineLoc, page, loc, fInlineLen);
node.garbage(node.garbage() + shrinkage + (fInlineLoc - loc));
}
/**
* Truncate the raw value which encodes a fragmented value.
*
* @return updated fHeaderLoc
*/
private static int truncateFragmented(final _Node node, final long page,
final int vHeaderLoc, final int vLen, int shrinkage)
{
final int newLen = vLen - shrinkage;
int loc = vHeaderLoc;
if (newLen <= 8192) {
p_bytePut(page, loc++, 0xc0 | ((newLen - 1) >> 8));
p_bytePut(page, loc++, newLen - 1);
if (vLen > 8192) {
// Reduced the header size.
p_copy(page, loc + 1, page, loc, newLen);
shrinkage++;
}
} else {
p_bytePut(page, loc++, 0xe0 | ((newLen - 1) >> 16));
p_bytePut(page, loc++, (newLen - 1) >> 8);
p_bytePut(page, loc++, newLen - 1);
}
node.garbage(node.garbage() + shrinkage);
return loc;
}
private static int pageSize(_LocalDatabase db, long page) {
// [
// return page.length;
// |
return db.pageSize();
// ]
}
}
|
package trabalho2;
/**
*
* @author daniellucredio
*/
public class LuazinhaSemanticAnalyzer extends LuazinhaBaseVisitor<Void> {
public static String grupo = "740951 743602 743586";
PilhaDeTabelas pilhaDeTabelas = new PilhaDeTabelas();
@Override
public Void visitPrograma(LuazinhaParser.ProgramaContext ctx) {
pilhaDeTabelas.empilhar(new TabelaDeSimbolos("global"));
super.visitPrograma(ctx);
// outro visitante, como a seguir:
//visitTrecho(ctx.trecho());
// do visitante (trecho)
// Cuidado para lembrar de inserir corretamente as chamadas
pilhaDeTabelas.desempilhar();
return null;
}
// esse efeito.
// @Override
// public Void visitBloco(LuazinhaParser.BlocoContext ctx) {
// super.visitBloco(ctx);
// visitTrecho(ctx.trecho());
// return null;
public Void visitComandoFunction(LuazinhaParser.ComandoFunctionContext ctx){
pilhaDeTabelas.empilhar(new TabelaDeSimbolos(ctx.nomedafuncao().nome));
super.visitComandoFunction(ctx);
pilhaDeTabelas.desempilhar();
return null;
}
public Void visitListavar(LuazinhaParser.ListavarContext ctx){
TabelaDeSimbolos tabela= pilhaDeTabelas.topo();
tabela.adicionarSimbolos(ctx.nomes,"variavel");
super.visitListavar(ctx);
return null;
}
}
|
package org.openecard.common.apdu.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.openecard.common.apdu.ReadBinary;
import org.openecard.common.apdu.ReadRecord;
import org.openecard.common.apdu.Select;
import org.openecard.common.apdu.Select.MasterFile;
import org.openecard.common.apdu.UpdateRecord;
import org.openecard.common.apdu.common.CardCommandAPDU;
import org.openecard.common.apdu.common.CardCommandStatus;
import org.openecard.common.apdu.common.CardResponseAPDU;
import org.openecard.common.apdu.exception.APDUException;
import org.openecard.common.interfaces.Dispatcher;
import org.openecard.common.tlv.TLVException;
import org.openecard.common.tlv.iso7816.DataElements;
import org.openecard.common.tlv.iso7816.FCP;
import org.openecard.common.util.ShortUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Moritz Horsch <horsch@cdc.informatik.tu-darmstadt.de>
* @author Dirk Petrautzki <petrautzki@hs-coburg.de>
* @author Simon Potzernheim <potzernheim@hs-coburg.de>
*/
public class CardUtils {
private static final Logger logger = LoggerFactory.getLogger(CardUtils.class);
/**
* Selects the Master File.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @throws APDUException
*/
public static void selectMF(Dispatcher dispatcher, byte[] slotHandle) throws APDUException {
CardCommandAPDU selectMF = new Select.MasterFile();
selectMF.transmit(dispatcher, slotHandle);
}
/**
* Selects a File.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @param fileID File ID
* @return The CardResponseAPDU from the selection of the file
* @throws APDUException
*/
public static CardResponseAPDU selectFile(Dispatcher dispatcher, byte[] slotHandle, short fileID) throws APDUException {
return selectFile(dispatcher, slotHandle, ShortUtils.toByteArray(fileID));
}
/**
* Selects a File.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @param fileID File ID
* @return CardREsponseAPDU containing the File Control Parameters
* @throws APDUException
*/
public static CardResponseAPDU selectFile(Dispatcher dispatcher, byte[] slotHandle, byte[] fileID) throws APDUException {
Select selectFile;
CardResponseAPDU result = null;
// respect the possibility that fileID could be a path
int i = 0;
while (i < fileID.length) {
if (fileID[0] == (byte) 0x3F && fileID[1] == (byte) 0x00) {
selectFile = new MasterFile();
i = i + 2;
} else if (i == fileID.length - 2) {
selectFile = new Select.ChildFile(new byte[]{fileID[i], fileID[i + 1]});
selectFile.setFCP();
i = i + 2;
} else {
selectFile = new Select.ChildDirectory(new byte[]{fileID[i], fileID[i + 1]});
i = i + 2;
}
result = selectFile.transmit(dispatcher, slotHandle);
}
return result;
}
/**
* Reads a file.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @param fcp File Control Parameters
* @return File content
* @throws APDUException
*/
public static byte[] readFile(FCP fcp, Dispatcher dispatcher, byte[] slotHandle) throws APDUException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Read 255 bytes per APDU
byte length = (byte) 0xFF;
int i = 0;
CardResponseAPDU response;
try {
do {
if (! isRecordEF(fcp)) {
CardCommandAPDU readBinary = new ReadBinary((short) (i * (length & 0xFF)), length);
// 0x6A84 code for the estonian identity card. The card returns this code
// after the last read process.
response = readBinary.transmit(dispatcher, slotHandle, CardCommandStatus.response(0x9000, 0x6282, 0x6A84));
} else {
CardCommandAPDU readRecord = new ReadRecord((byte) i);
response = readRecord.transmit(dispatcher, slotHandle, CardCommandStatus.response(0x9000, 0x6282));
}
if (! Arrays.equals(response.getTrailer(), new byte[] {(byte) 0x6A, (byte) 0x84})) {
baos.write(response.getData());
}
i++;
} while (response.isNormalProcessed());
baos.close();
} catch (IOException e) {
throw new APDUException(e);
}
return baos.toByteArray();
}
/**
* Selects and reads a file.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @param fileID File ID
* @return File content
* @throws APDUException
*/
@Deprecated
public static byte[] readFile(Dispatcher dispatcher, byte[] slotHandle, short fileID) throws APDUException {
return readFile(dispatcher, slotHandle, ShortUtils.toByteArray(fileID));
}
/**
* Selects and reads a file.
*
* @param dispatcher Dispatcher
* @param slotHandle Slot handle
* @param fileID File ID
* @return File content
* @throws APDUException
*/
@Deprecated
public static byte[] readFile(Dispatcher dispatcher, byte[] slotHandle, byte[] fileID) throws APDUException {
CardResponseAPDU selectResponse = selectFile(dispatcher, slotHandle, fileID);
FCP fcp = null;
try {
fcp = new FCP(selectResponse.getData());
} catch (TLVException e) {
logger.warn("Couldn't get File Control Parameters from Select response.", e);
}
return readFile(fcp, dispatcher, slotHandle);
}
public static byte[] selectReadFile(Dispatcher dispatcher, byte[] slotHandle, short fileID) throws APDUException {
return readFile(dispatcher, slotHandle, fileID);
}
public static byte[] selectReadFile(Dispatcher dispatcher, byte[] slotHandle, byte[] fileID) throws APDUException {
return readFile(dispatcher, slotHandle, fileID);
}
private static boolean isRecordEF(FCP fcp) {
if (fcp == null) {
// TODO inspect EF.ATR as described in ISO/IEC 7816-4 Section 8.4
return false;
} else {
DataElements dataElements = fcp.getDataElements();
if (dataElements.isLinear() || dataElements.isCyclic()) {
return true;
} else {
return false;
}
}
}
public static void writeFile(Dispatcher dispatcher, byte[] slotHandle, byte[] fileID, byte[] data) throws APDUException {
CardResponseAPDU selectResponse = selectFile(dispatcher, slotHandle, fileID);
FCP fcp = null;
try {
fcp = new FCP(selectResponse.getData());
} catch (TLVException e) {
logger.warn("Couldn't get File Control Parameters from Select response.", e);
}
writeFile(fcp, dispatcher, slotHandle, data);
}
private static void writeFile(FCP fcp, Dispatcher dispatcher, byte[] slotHandle, byte[] data) throws APDUException {
if (isRecordEF(fcp)) {
UpdateRecord updateRecord = new UpdateRecord(data);
updateRecord.transmit(dispatcher, slotHandle);
} else {
// TODO implement writing for non record files
throw new UnsupportedOperationException("Not yet implemented.");
}
}
}
|
package com.apptentive.android.sdk.conversation;
import android.content.Context;
import android.content.SharedPreferences;
import com.apptentive.android.sdk.Apptentive;
import com.apptentive.android.sdk.Apptentive.LoginCallback;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.ApptentiveLog;
import com.apptentive.android.sdk.comm.ApptentiveHttpClient;
import com.apptentive.android.sdk.conversation.ConversationMetadata.Filter;
import com.apptentive.android.sdk.migration.Migrator;
import com.apptentive.android.sdk.model.ConversationItem;
import com.apptentive.android.sdk.model.ConversationTokenRequest;
import com.apptentive.android.sdk.module.engagement.EngagementModule;
import com.apptentive.android.sdk.network.HttpJsonRequest;
import com.apptentive.android.sdk.network.HttpRequest;
import com.apptentive.android.sdk.notifications.ApptentiveNotification;
import com.apptentive.android.sdk.notifications.ApptentiveNotificationCenter;
import com.apptentive.android.sdk.notifications.ApptentiveNotificationObserver;
import com.apptentive.android.sdk.serialization.ObjectSerialization;
import com.apptentive.android.sdk.storage.AppRelease;
import com.apptentive.android.sdk.storage.AppReleaseManager;
import com.apptentive.android.sdk.storage.Device;
import com.apptentive.android.sdk.storage.DeviceManager;
import com.apptentive.android.sdk.storage.Sdk;
import com.apptentive.android.sdk.storage.SdkManager;
import com.apptentive.android.sdk.storage.SerializerException;
import com.apptentive.android.sdk.util.Constants;
import com.apptentive.android.sdk.util.Jwt;
import com.apptentive.android.sdk.util.ObjectUtils;
import com.apptentive.android.sdk.util.StringUtils;
import com.apptentive.android.sdk.util.Util;
import com.apptentive.android.sdk.util.threading.DispatchQueue;
import com.apptentive.android.sdk.util.threading.DispatchTask;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import static com.apptentive.android.sdk.ApptentiveLog.Level.VERY_VERBOSE;
import static com.apptentive.android.sdk.ApptentiveLogTag.*;
import static com.apptentive.android.sdk.ApptentiveNotifications.*;
import static com.apptentive.android.sdk.conversation.ConversationState.*;
import static com.apptentive.android.sdk.debug.Assert.*;
import static com.apptentive.android.sdk.debug.Tester.*;
import static com.apptentive.android.sdk.debug.TesterEvent.*;
import static com.apptentive.android.sdk.util.StringUtils.isNullOrEmpty;
/**
* Class responsible for managing conversations.
* <pre>
* - Saving/Loading conversations from/to files.
* - Switching conversations when users login/logout.
* - Creating anonymous conversation.
* </pre>
*/
public class ConversationManager {
protected static final String CONVERSATION_METADATA_PATH = "conversation-v1.meta";
private static final String TAG_FETCH_CONVERSATION_TOKEN_REQUEST = "fetch_conversation_token";
private final WeakReference<Context> contextRef;
/**
* A basic directory for storing conversation-related data.
*/
private final File apptentiveConversationsStorageDir;
/**
* Current state of conversation metadata.
*/
private ConversationMetadata conversationMetadata;
private Conversation activeConversation;
public ConversationManager(Context context, File apptentiveConversationsStorageDir) {
if (context == null) {
throw new IllegalArgumentException("Context is null");
}
this.contextRef = new WeakReference<>(context.getApplicationContext());
this.apptentiveConversationsStorageDir = apptentiveConversationsStorageDir;
ApptentiveNotificationCenter.defaultCenter()
.addObserver(NOTIFICATION_APP_ENTERED_FOREGROUND, new ApptentiveNotificationObserver() {
@Override
public void onReceiveNotification(ApptentiveNotification notification) {
assertMainThread();
if (activeConversation != null && activeConversation.hasActiveState()) {
ApptentiveLog.v(CONVERSATION, "App entered foreground notification received. Trying to fetch interactions...");
final Context context = getContext();
if (context != null) {
activeConversation.fetchInteractions(context);
} else {
ApptentiveLog.w(CONVERSATION, "Can't fetch conversation interactions: context is lost");
}
}
}
});
}
//region Conversations
/**
* Attempts to load an active conversation. Returns <code>false</code> if active conversation is
* missing or cannot be loaded
*/
public boolean loadActiveConversation(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context is null");
}
try {
assertMainThread();
// resolving metadata
ApptentiveLog.vv(CONVERSATION, "Resolving metadata...");
conversationMetadata = resolveMetadata();
if (ApptentiveLog.canLog(VERY_VERBOSE)) {
printMetadata(conversationMetadata, "Loaded Metadata");
}
// attempt to load existing conversation
ApptentiveLog.vv(CONVERSATION, "Loading active conversation...");
activeConversation = loadActiveConversationGuarded();
if (activeConversation != null) {
dispatchDebugEvent(EVT_CONVERSATION_LOAD,
"successful", Boolean.TRUE,
"conversation_state", activeConversation.getState().toString(),
"conversation_identifier", activeConversation.getConversationId());
handleConversationStateChange(activeConversation);
return true;
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while loading active conversation");
}
dispatchDebugEvent(EVT_CONVERSATION_LOAD, "successful", Boolean.FALSE);
return false;
}
private Conversation loadActiveConversationGuarded() throws IOException, SerializerException {
// we're going to scan metadata in attempt to find existing conversations
ConversationMetadataItem item;
// if the user was logged in previously - we should have an active conversation
item = conversationMetadata.findItem(LOGGED_IN);
if (item != null) {
ApptentiveLog.v(CONVERSATION, "Loading logged-in conversation...");
return loadConversation(item);
}
// if no users were logged in previously - we might have an anonymous conversation
item = conversationMetadata.findItem(ANONYMOUS);
if (item != null) {
ApptentiveLog.v(CONVERSATION, "Loading anonymous conversation...");
return loadConversation(item);
}
// check if we have a 'pending' anonymous conversation
item = conversationMetadata.findItem(ANONYMOUS_PENDING);
if (item != null) {
ApptentiveLog.v(CONVERSATION, "Loading anonymous pending conversation...");
final Conversation conversation = loadConversation(item);
fetchConversationToken(conversation);
return conversation;
}
// check if we have a 'legacy pending' conversation
item = conversationMetadata.findItem(LEGACY_PENDING);
if (item != null) {
ApptentiveLog.v(CONVERSATION, "Loading legacy pending conversation...");
final Conversation conversation = loadConversation(item);
fetchLegacyConversation(conversation);
return conversation;
}
// Check for only LOGGED_OUT Conversations
if (conversationMetadata.hasItems()) {
ApptentiveLog.v(CONVERSATION, "Can't load conversation: only 'logged-out' conversations available");
return null;
}
// No conversation exists: Create a new one
ApptentiveLog.v(CONVERSATION, "Can't load conversation: creating anonymous conversation...");
File dataFile = new File(apptentiveConversationsStorageDir, "conversation-" + Util.generateRandomFilename());
File messagesFile = new File(apptentiveConversationsStorageDir, "messages-" + Util.generateRandomFilename());
Conversation anonymousConversation = new Conversation(dataFile, messagesFile);
// If there is a Legacy Conversation, migrate it into the new Conversation object.
// Check whether migration is needed.
// No Conversations exist in the meta-data.
// Do we have a Legacy Conversation or not?
final SharedPreferences prefs = ApptentiveInternal.getInstance().getGlobalSharedPrefs();
String legacyConversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
if (!isNullOrEmpty(legacyConversationToken)) {
String lastSeenVersionString = prefs.getString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, null);
Apptentive.Version version4 = new Apptentive.Version();
version4.setVersion("4.0.0");
Apptentive.Version lastSeenVersion = new Apptentive.Version();
lastSeenVersion.setVersion(lastSeenVersionString);
if (lastSeenVersionString != null && lastSeenVersion.compareTo(version4) < 0) {
anonymousConversation.setState(LEGACY_PENDING);
anonymousConversation.setConversationToken(legacyConversationToken);
Migrator migrator = new Migrator(getContext(), prefs, anonymousConversation);
migrator.migrate();
ApptentiveLog.v("Fetching legacy conversation...");
fetchLegacyConversation(anonymousConversation)
// remove legacy key when request is finished
.addListener(new HttpRequest.Adapter<HttpRequest>() {
@Override
public void onFinish(HttpRequest request) {
prefs.edit()
.remove(Constants.PREF_KEY_CONVERSATION_TOKEN)
.apply();
}
});
return anonymousConversation;
}
}
// If there is no Legacy Conversation, then just connect it to the server.
anonymousConversation.setState(ANONYMOUS_PENDING);
fetchConversationToken(anonymousConversation);
return anonymousConversation;
}
private HttpRequest fetchLegacyConversation(final Conversation conversation) {
assertNotNull(conversation);
if (conversation == null) {
throw new IllegalArgumentException("Conversation is null");
}
assertEquals(conversation.getState(), ConversationState.LEGACY_PENDING);
final String conversationToken = conversation.getConversationToken();
if (isNullOrEmpty(conversationToken)) {
throw new IllegalStateException("Missing conversation token");
}
assertFalse(isNullOrEmpty(conversationToken));
if (isNullOrEmpty(conversationToken)) {
throw new IllegalArgumentException("Conversation is null");
}
HttpRequest request = getHttpClient()
.createLegacyConversationIdRequest(conversationToken, new HttpRequest.Listener<HttpJsonRequest>() {
@Override
public void onFinish(HttpJsonRequest request) {
assertMainThread();
try {
JSONObject root = request.getResponseObject();
String conversationId = root.getString("conversation_id");
ApptentiveLog.d(CONVERSATION, "Conversation id: %s", conversationId);
if (isNullOrEmpty(conversationId)) {
ApptentiveLog.e(CONVERSATION, "Can't fetch legacy conversation: missing 'id'");
return;
}
String conversationJWT = root.getString("anonymous_jwt_token");
if (isNullOrEmpty(conversationId)) {
ApptentiveLog.e(CONVERSATION, "Can't fetch legacy conversation: missing 'anonymous_jwt_token'");
return;
}
ApptentiveLog.d(CONVERSATION, "Conversation JWT: %s", conversationJWT);
// set conversation data
conversation.setState(ANONYMOUS);
conversation.setConversationToken(conversationJWT);
conversation.setConversationId(conversationId);
// handle state change
handleConversationStateChange(conversation);
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while handling legacy conversation id");
}
}
@Override
public void onCancel(HttpJsonRequest request) {
}
@Override
public void onFail(HttpJsonRequest request, String reason) {
ApptentiveLog.e("Failed to fetch legacy conversation id: %s", reason);
}
});
request.setCallbackQueue(DispatchQueue.mainQueue()); // we only deal with conversation on the main queue
request.setTag(TAG_FETCH_CONVERSATION_TOKEN_REQUEST);
request.start();
return request;
}
private Conversation loadConversation(ConversationMetadataItem item) throws SerializerException {
// TODO: use same serialization logic across the project
final Conversation conversation = new Conversation(item.dataFile, item.messagesFile);
conversation.setEncryptionKey(item.getEncryptionKey()); // it's important to set encryption key before loading data
conversation.setState(item.getState()); // set the state same as the item's state
conversation.setUserId(item.getUserId());
conversation.setConversationToken(item.getConversationToken());
conversation.loadConversationData();
conversation.checkInternalConsistency();
return conversation;
}
//endregion
//region Conversation Token Fetching
/**
* Starts fetching conversation. Returns immediately if conversation is already fetching.
*
* @return a new http-request object if conversation is not currently fetched or an instance of
* the existing request
*/
private HttpRequest fetchConversationToken(final Conversation conversation) {
// check if context is lost
final Context context = getContext();
if (context == null) {
ApptentiveLog.w(CONVERSATION, "Unable to fetch conversation token: context reference is lost");
return null;
}
// check for an existing request
HttpRequest existingRequest = getHttpClient().findRequest(TAG_FETCH_CONVERSATION_TOKEN_REQUEST);
if (existingRequest != null) {
ApptentiveLog.d(CONVERSATION, "Conversation already fetching");
return existingRequest;
}
ApptentiveLog.i(CONVERSATION, "Fetching Configuration token task started.");
dispatchDebugEvent(EVT_CONVERSATION_WILL_FETCH_TOKEN);
// Try to fetch a new one from the server.
ConversationTokenRequest conversationTokenRequest = new ConversationTokenRequest();
// Send the Device and Sdk now, so they are available on the server from the start.
final Device device = DeviceManager.generateNewDevice(context);
final Sdk sdk = SdkManager.generateCurrentSdk();
final AppRelease appRelease = ApptentiveInternal.getInstance().getAppRelease();
conversationTokenRequest.setDevice(DeviceManager.getDiffPayload(null, device));
conversationTokenRequest.setSdkAndAppRelease(SdkManager.getPayload(sdk), AppReleaseManager.getPayload(appRelease));
HttpRequest request = getHttpClient()
.createConversationTokenRequest(conversationTokenRequest, new HttpRequest.Listener<HttpJsonRequest>() {
@Override
public void onFinish(HttpJsonRequest request) {
assertMainThread();
try {
JSONObject root = request.getResponseObject();
String conversationToken = root.getString("token");
ApptentiveLog.d(CONVERSATION, "ConversationToken: " + conversationToken);
String conversationId = root.getString("id");
ApptentiveLog.d(CONVERSATION, "New Conversation id: %s", conversationId);
if (isNullOrEmpty(conversationToken)) {
ApptentiveLog.e(CONVERSATION, "Can't fetch conversation: missing 'token'");
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, false);
return;
}
if (isNullOrEmpty(conversationId)) {
ApptentiveLog.e(CONVERSATION, "Can't fetch conversation: missing 'id'");
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, false);
return;
}
// set conversation data
conversation.setState(ANONYMOUS);
conversation.setConversationToken(conversationToken);
conversation.setConversationId(conversationId);
conversation.setDevice(device);
conversation.setLastSentDevice(device.clone());
conversation.setAppRelease(appRelease);
conversation.setSdk(sdk);
conversation.setLastSeenSdkVersion(sdk.getVersion());
String personId = root.getString("person_id");
ApptentiveLog.d(CONVERSATION, "PersonId: " + personId);
conversation.getPerson().setId(personId);
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, true);
handleConversationStateChange(conversation);
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while handling conversation token");
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, false);
}
}
@Override
public void onCancel(HttpJsonRequest request) {
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, false);
}
@Override
public void onFail(HttpJsonRequest request, String reason) {
ApptentiveLog.w("Failed to fetch conversation token: %s", reason);
dispatchDebugEvent(EVT_CONVERSATION_DID_FETCH_TOKEN, false);
}
});
request.setCallbackQueue(DispatchQueue.mainQueue()); // we only deal with conversation on the main queue
request.setTag(TAG_FETCH_CONVERSATION_TOKEN_REQUEST);
request.start();
return request;
}
//endregion
//region Conversation fetching
private void handleConversationStateChange(Conversation conversation) {
assertMainThread();
assertTrue(conversation != null && !conversation.hasState(UNDEFINED));
if (conversation != null && !conversation.hasState(UNDEFINED)) {
dispatchDebugEvent(EVT_CONVERSATION_STATE_CHANGE,
"conversation_state", conversation.getState().toString(),
"conversation_identifier", conversation.getConversationId());
ApptentiveNotificationCenter.defaultCenter()
.postNotification(NOTIFICATION_CONVERSATION_STATE_DID_CHANGE,
ObjectUtils.toMap(NOTIFICATION_KEY_CONVERSATION, conversation));
if (conversation.hasActiveState()) {
conversation.fetchInteractions(getContext());
conversation.getMessageManager().startPollingMessages();
// Update conversation with push configuration changes that happened while it wasn't active.
SharedPreferences prefs = ApptentiveInternal.getInstance().getGlobalSharedPrefs();
int pushProvider = prefs.getInt(Constants.PREF_KEY_PUSH_PROVIDER, -1);
String pushToken = prefs.getString(Constants.PREF_KEY_PUSH_TOKEN, null);
if (pushProvider != -1 && pushToken != null) {
conversation.setPushIntegration(pushProvider, pushToken);
}
}
updateMetadataItems(conversation);
if (ApptentiveLog.canLog(VERY_VERBOSE)) {
printMetadata(conversationMetadata, "Updated Metadata");
}
}
}
/* For testing purposes */
public synchronized boolean setActiveConversation(final String conversationId) throws SerializerException {
final ConversationMetadataItem item = conversationMetadata.findItem(new Filter() {
@Override
public boolean accept(ConversationMetadataItem item) {
return item.conversationId.equals(conversationId);
}
});
if (item == null) {
ApptentiveLog.w(CONVERSATION, "Conversation not found: %s", conversationId);
return false;
}
final Conversation conversation = loadConversation(item);
if (conversation == null) {
ApptentiveLog.w(CONVERSATION, "Conversation not loaded: %s", conversationId);
return false;
}
handleConversationStateChange(conversation);
return true;
}
private void updateMetadataItems(Conversation conversation) {
ApptentiveLog.vv("Updating metadata: state=%s localId=%s conversationId=%s token=%s",
conversation.getState(),
conversation.getLocalIdentifier(),
conversation.getConversationId(),
conversation.getConversationToken());
// if the conversation is 'logged-in' we should not have any other 'logged-in' items in metadata
if (conversation.hasState(LOGGED_IN)) {
for (ConversationMetadataItem item : conversationMetadata) {
if (item.state.equals(LOGGED_IN)) {
item.state = LOGGED_OUT;
}
}
}
// delete sensitive information
for (ConversationMetadataItem item : conversationMetadata) {
item.encryptionKey = null;
item.conversationToken = null;
}
// update the state of the corresponding item
ConversationMetadataItem item = conversationMetadata.findItem(conversation);
if (item == null) {
item = new ConversationMetadataItem(conversation.getLocalIdentifier(), conversation.getConversationId(), conversation.getConversationDataFile(), conversation.getConversationMessagesFile());
conversationMetadata.addItem(item);
} else {
assertTrue(conversation.getConversationId() != null || conversation.hasState(ANONYMOUS_PENDING), "Missing conversation id for state: %s", conversation.getState());
item.conversationId = conversation.getConversationId();
}
item.state = conversation.getState();
if (conversation.hasActiveState()) {
item.conversationToken = notNull(conversation.getConversationToken());
}
// update encryption key (if necessary)
if (conversation.hasState(LOGGED_IN)) {
item.encryptionKey = notNull(conversation.getEncryptionKey());
item.userId = notNull(conversation.getUserId());
}
// apply changes
saveMetadata();
}
//endregion
//region Metadata
private ConversationMetadata resolveMetadata() {
try {
File metaFile = new File(apptentiveConversationsStorageDir, CONVERSATION_METADATA_PATH);
if (metaFile.exists()) {
ApptentiveLog.v(CONVERSATION, "Loading meta file: " + metaFile);
final ConversationMetadata metadata = ObjectSerialization.deserialize(metaFile, ConversationMetadata.class);
dispatchDebugEvent(EVT_CONVERSATION_METADATA_LOAD, true);
return metadata;
} else {
ApptentiveLog.v(CONVERSATION, "Meta file does not exist: " + metaFile);
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while loading conversation metadata");
}
dispatchDebugEvent(EVT_CONVERSATION_METADATA_LOAD, false);
return new ConversationMetadata();
}
private void saveMetadata() {
try {
if (ApptentiveLog.canLog(VERY_VERBOSE)) {
ApptentiveLog.vv(CONVERSATION, "Saving metadata: ", conversationMetadata.toString());
}
long start = System.currentTimeMillis();
File metaFile = new File(apptentiveConversationsStorageDir, CONVERSATION_METADATA_PATH);
ObjectSerialization.serialize(metaFile, conversationMetadata);
ApptentiveLog.v(CONVERSATION, "Saved metadata (took %d ms)", System.currentTimeMillis() - start);
} catch (Exception e) {
ApptentiveLog.e(CONVERSATION, "Exception while saving metadata");
}
}
//endregion
//region Login/Logout
private static final LoginCallback NULL_LOGIN_CALLBACK = new LoginCallback() {
@Override
public void onLoginFinish() {
}
@Override
public void onLoginFail(String errorMessage) {
}
};
public void login(final String token, final LoginCallback callback) {
// we only deal with an active conversation on the main thread
if (DispatchQueue.isMainQueue()) {
requestLoggedInConversation(token, callback != null ? callback : NULL_LOGIN_CALLBACK); // avoid constant null-pointer checking
} else {
DispatchQueue.mainQueue().dispatchAsync(new DispatchTask() {
@Override
protected void execute() {
requestLoggedInConversation(token, callback != null ? callback : NULL_LOGIN_CALLBACK); // avoid constant null-pointer checking
}
});
}
}
private void requestLoggedInConversation(final String token, final LoginCallback callback) {
assertMainThread();
if (callback == null) {
throw new IllegalArgumentException("Callback is null");
}
final String userId;
try {
final Jwt jwt = Jwt.decode(token);
userId = jwt.getPayload().optString("sub");
if (StringUtils.isNullOrEmpty(userId)) {
ApptentiveLog.e("Error while extracting user id: Missing field \"sub\"");
callback.onLoginFail("Error while extracting user id: Missing field \"sub\"");
return;
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while extracting user id");
callback.onLoginFail("Exception while extracting user id");
return;
}
assertMainThread();
// Check if there is an active conversation
if (activeConversation == null) {
ApptentiveLog.d(CONVERSATION, "No active conversation. Performing login...");
// attempt to find previous logged out conversation
final ConversationMetadataItem conversationItem = conversationMetadata.findItem(new Filter() {
@Override
public boolean accept(ConversationMetadataItem item) {
return StringUtils.equal(item.getUserId(), userId);
}
});
if (conversationItem == null) {
ApptentiveLog.w("No conversation found matching user: '%s'. Logging in as new user.", userId);
sendLoginRequest(null, userId, token, callback);
return;
}
sendLoginRequest(conversationItem.conversationId, userId, token, callback);
return;
}
switch (activeConversation.getState()) {
case ANONYMOUS_PENDING:
case LEGACY_PENDING: {
// start fetching conversation token (if not yet fetched)
final HttpRequest fetchRequest = activeConversation.hasState(ANONYMOUS_PENDING) ?
fetchConversationToken(activeConversation) :
fetchLegacyConversation(activeConversation);
if (fetchRequest == null) {
ApptentiveLog.e(CONVERSATION, "Unable to login: fetch request failed to send");
callback.onLoginFail("fetch request failed to send");
return;
}
// attach a listener to an active request
fetchRequest.addListener(new HttpRequest.Listener<HttpRequest>() {
@Override
public void onFinish(HttpRequest request) {
assertMainThread();
assertTrue(activeConversation != null && activeConversation.hasState(ANONYMOUS), "Active conversation is missing or in a wrong state: %s", activeConversation);
if (activeConversation != null && activeConversation.hasState(ANONYMOUS)) {
ApptentiveLog.d(CONVERSATION, "Conversation fetching complete. Performing login...");
sendLoginRequest(activeConversation.getConversationId(), userId, token, callback);
} else {
callback.onLoginFail("Conversation fetching completed abnormally");
}
}
@Override
public void onCancel(HttpRequest request) {
ApptentiveLog.d(CONVERSATION, "Unable to login: conversation fetching cancelled.");
callback.onLoginFail("Conversation fetching was cancelled");
}
@Override
public void onFail(HttpRequest request, String reason) {
ApptentiveLog.d(CONVERSATION, "Unable to login: conversation fetching failed.");
callback.onLoginFail("Conversation fetching failed: " + reason);
}
});
}
break;
case ANONYMOUS:
sendLoginRequest(activeConversation.getConversationId(), userId, token, callback);
break;
case LOGGED_IN:
if (StringUtils.equal(activeConversation.getUserId(), userId)) {
ApptentiveLog.w("Already logged in as \"%s\"", userId);
callback.onLoginFinish();
return;
}
// FIXME: If they are attempting to login to a different conversation, we need to gracefully end the active conversation here and kick off a login request to the desired conversation.
callback.onLoginFail("Already logged in. You must log out first.");
break;
default:
assertFail("Unexpected conversation state: " + activeConversation.getState());
callback.onLoginFail("internal error");
break;
}
}
private void sendLoginRequest(String conversationId, final String userId, final String token, final LoginCallback callback) {
HttpJsonRequest request = getHttpClient().createLoginRequest(conversationId, token, new HttpRequest.Listener<HttpJsonRequest>() {
@Override
public void onFinish(HttpJsonRequest request) {
try {
final JSONObject responseObject = request.getResponseObject();
final String encryptionKey = responseObject.getString("encryption_key");
final String incomingConversationId = responseObject.getString("id");
handleLoginFinished(incomingConversationId, userId, token, encryptionKey);
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while parsing login response");
handleLoginFailed("Internal error");
}
}
@Override
public void onCancel(HttpJsonRequest request) {
handleLoginFailed("Login request was cancelled");
}
@Override
public void onFail(HttpJsonRequest request, String reason) {
handleLoginFailed(reason);
}
private void handleLoginFinished(final String conversationId, final String userId, final String token, final String encryptionKey) {
DispatchQueue.mainQueue().dispatchAsync(new DispatchTask() {
@Override
protected void execute() {
assertFalse(isNullOrEmpty(encryptionKey),"Login finished with missing encryption key.");
assertFalse(isNullOrEmpty(token), "Login finished with missing token.");
assertMainThread();
try {
// if we were previously logged out we might end up with no active conversation
if (activeConversation == null) {
// attempt to find previous logged out conversation
final ConversationMetadataItem conversationItem = conversationMetadata.findItem(new Filter() {
@Override
public boolean accept(ConversationMetadataItem item) {
return StringUtils.equal(item.getUserId(), userId);
}
});
if (conversationItem != null) {
conversationItem.conversationToken = token;
conversationItem.encryptionKey = encryptionKey;
activeConversation = loadConversation(conversationItem);
} else {
ApptentiveLog.v(CONVERSATION, "Creating new logged in conversation...");
File dataFile = new File(apptentiveConversationsStorageDir, "conversation-" + Util.generateRandomFilename());
File messagesFile = new File(apptentiveConversationsStorageDir, "messages-" + Util.generateRandomFilename());
activeConversation = new Conversation(dataFile, messagesFile);
// FIXME: if we don't set these here - device payload would return 4xx error code
activeConversation.setDevice(DeviceManager.generateNewDevice(getContext()));
activeConversation.setAppRelease(ApptentiveInternal.getInstance().getAppRelease());
activeConversation.setSdk(SdkManager.generateCurrentSdk());
}
}
activeConversation.setEncryptionKey(encryptionKey);
activeConversation.setConversationToken(token);
activeConversation.setConversationId(conversationId);
activeConversation.setUserId(userId);
activeConversation.setState(LOGGED_IN);
handleConversationStateChange(activeConversation);
// notify delegate
callback.onLoginFinish();
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while creating logged-in conversation");
handleLoginFailed("Internal error");
}
}
});
}
private void handleLoginFailed(final String reason) {
DispatchQueue.mainQueue().dispatchAsync(new DispatchTask() {
@Override
protected void execute() {
callback.onLoginFail(reason);
}
});
}
});
request.start();
}
public void logout() {
// we only deal with an active conversation on the main thread
if (!DispatchQueue.isMainQueue()) {
DispatchQueue.mainQueue().dispatchAsync(new DispatchTask() {
@Override
protected void execute() {
doLogout();
}
});
} else {
doLogout();
}
}
private void doLogout() {
assertMainThread();
if (activeConversation != null) {
switch (activeConversation.getState()) {
case LOGGED_IN:
ApptentiveLog.d("Ending active conversation.");
EngagementModule.engageInternal(getContext(), activeConversation, "logout");
// Post synchronously to ensure logout payload can be sent before destroying the logged in conversation.
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_CONVERSATION_WILL_LOGOUT, ObjectUtils.toMap(NOTIFICATION_KEY_CONVERSATION, activeConversation));
activeConversation.destroy();
activeConversation.setState(LOGGED_OUT);
handleConversationStateChange(activeConversation);
activeConversation = null;
ApptentiveInternal.dismissAllInteractions();
break;
default:
ApptentiveLog.w(CONVERSATION, "Attempted to logout() from Conversation, but the Active Conversation was not in LOGGED_IN state.");
break;
}
} else {
ApptentiveLog.w(CONVERSATION, "Attempted to logout(), but there was no Active Conversation.");
}
dispatchDebugEvent(EVT_LOGOUT);
}
//endregion
//region Debug
private void printMetadata(ConversationMetadata metadata, String title) {
List<ConversationMetadataItem> items = metadata.getItems();
if (items.isEmpty()) {
ApptentiveLog.vv(CONVERSATION, "%s (%d item(s))", title, items.size());
return;
}
Object[][] rows = new Object[1 + items.size()][];
rows[0] = new Object[] {
"state",
"localId",
"conversationId",
"userId",
"dataFile",
"messagesFile",
"conversationToken",
"encryptionKey"
};
int index = 1;
for (ConversationMetadataItem item : items) {
rows[index++] = new Object[] {
item.state,
item.localConversationId,
item.conversationId,
item.userId,
item.dataFile,
item.messagesFile,
item.conversationToken,
item.encryptionKey
};
}
ApptentiveLog.vv(CONVERSATION, "%s (%d item(s))\n%s", title, items.size(), StringUtils.table(rows));
}
//endregion
//region Getters/Setters
public Conversation getActiveConversation() {
assertMainThread();
return activeConversation;
}
public ConversationMetadata getConversationMetadata() {
return conversationMetadata;
}
private ApptentiveHttpClient getHttpClient() {
return ApptentiveInternal.getInstance().getApptentiveHttpClient(); // TODO: remove coupling
}
private Context getContext() {
return contextRef.get();
}
//endregion
}
|
package com.proofpoint.concurrent;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.proofpoint.units.Duration;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Throwables.propagateIfPossible;
import static com.google.common.base.Throwables.throwIfInstanceOf;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.common.util.concurrent.Futures.catchingAsync;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.withTimeout;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public final class MoreFutures
{
private MoreFutures() { }
/**
* Cancels the destination Future if the source Future is cancelled.
*/
public static <X, Y> void propagateCancellation(ListenableFuture<? extends X> source, Future<? extends Y> destination, boolean mayInterruptIfRunning)
{
source.addListener(() -> {
if (source.isCancelled()) {
destination.cancel(mayInterruptIfRunning);
}
}, directExecutor());
}
/**
* Mirrors all results of the source Future to the destination Future.
* <p>
* This also propagates cancellations from the destination Future back to the source Future.
*/
public static <T> void mirror(ListenableFuture<? extends T> source, SettableFuture<? super T> destination, boolean mayInterruptIfRunning)
{
Futures.addCallback(source, new FutureCallback<T>()
{
@Override
public void onSuccess(@Nullable T result)
{
destination.set(result);
}
@Override
public void onFailure(Throwable t)
{
destination.setException(t);
}
});
propagateCancellation(destination, source, mayInterruptIfRunning);
}
/**
* Attempts to unwrap a throwable that has been wrapped in a {@link CompletionException}.
*/
public static Throwable unwrapCompletionException(Throwable throwable)
{
if (throwable instanceof CompletionException) {
return firstNonNull(throwable.getCause(), throwable);
}
return throwable;
}
/**
* Returns a future that can not be completed or canceled.
*/
public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future)
{
return unmodifiableFuture(future, false);
}
/**
* Returns a future that can not be completed or optionally canceled.
*/
public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future, boolean propagateCancel)
{
requireNonNull(future, "future is null");
Function<Boolean, Boolean> onCancelFunction;
if (propagateCancel) {
onCancelFunction = future::cancel;
}
else {
onCancelFunction = mayInterrupt -> false;
}
UnmodifiableCompletableFuture<V> unmodifiableFuture = new UnmodifiableCompletableFuture<>(onCancelFunction);
future.whenComplete((value, exception) -> {
if (exception != null) {
unmodifiableFuture.internalCompleteExceptionally(exception);
}
else {
unmodifiableFuture.internalComplete(value);
}
});
return unmodifiableFuture;
}
/**
* Returns a failed future containing the specified throwable.
*/
public static <V> CompletableFuture<V> failedFuture(Throwable throwable)
{
requireNonNull(throwable, "throwable is null");
CompletableFuture<V> future = new CompletableFuture<>();
future.completeExceptionally(throwable);
return future;
}
/**
* Waits for the value from the future. If the future is failed, the exception
* is thrown directly if unchecked or wrapped in a RuntimeException. If the
* thread is interrupted, the thread interruption flag is set and the original
* InterruptedException is wrapped in a RuntimeException and thrown.
*/
public static <V> V getFutureValue(Future<V> future)
{
return getFutureValue(future, RuntimeException.class);
}
/**
* Waits for the value from the future. If the future is failed, the exception
* is thrown directly if it is an instance of the specified exception type or
* unchecked, or it is wrapped in a RuntimeException. If the thread is
* interrupted, the thread interruption flag is set and the original
* InterruptedException is wrapped in a RuntimeException and thrown.
*/
public static <V, E extends Exception> V getFutureValue(Future<V> future, Class<E> exceptionType)
throws E
{
requireNonNull(future, "future is null");
requireNonNull(exceptionType, "exceptionType is null");
try {
return future.get();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted", e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
propagateIfPossible(cause, exceptionType);
throw new RuntimeException(cause);
}
}
/**
* Gets the current value of the future without waiting. If the future
* value is null, an empty Optional is still returned, and in this case the caller
* must check the future directly for the null value.
*/
public static <T> Optional<T> tryGetFutureValue(Future<T> future)
{
requireNonNull(future, "future is null");
if (!future.isDone()) {
return Optional.empty();
}
return tryGetFutureValue(future, 0, MILLISECONDS);
}
/**
* Waits for the the value from the future for the specified time. If the future
* value is null, an empty Optional is still returned, and in this case the caller
* must check the future directly for the null value. If the future is failed,
* the exception is thrown directly if unchecked or wrapped in a RuntimeException.
* If the thread is interrupted, the thread interruption flag is set and the original
* InterruptedException is wrapped in a RuntimeException and thrown.
*/
public static <V> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit)
{
return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class);
}
/**
* Waits for the the value from the future for the specified time. If the future
* value is null, an empty Optional is still returned, and in this case the caller
* must check the future directly for the null value. If the future is failed,
* the exception is thrown directly if it is an instance of the specified exception
* type or unchecked, or it is wrapped in a RuntimeException. If the thread is
* interrupted, the thread interruption flag is set and the original
* InterruptedException is wrapped in a RuntimeException and thrown.
*/
public static <V, E extends Exception> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit, Class<E> exceptionType)
throws E
{
requireNonNull(future, "future is null");
checkArgument(timeout >= 0, "timeout is negative");
requireNonNull(timeUnit, "timeUnit is null");
requireNonNull(exceptionType, "exceptionType is null");
try {
return Optional.ofNullable(future.get(timeout, timeUnit));
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted", e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
propagateIfPossible(cause, exceptionType);
throw new RuntimeException(cause);
}
catch (TimeoutException expected) {
// expected
}
return Optional.empty();
}
/**
* Returns the result of the input {@link Future}, which must have already completed.
* <p>
* Similar to Futures{@link Futures#getDone(Future)}, but does not throw checked exceptions.
*/
public static <T> T getDone(Future<T> future)
{
requireNonNull(future, "future is null");
checkArgument(future.isDone(), "future not done yet");
return getFutureValue(future);
}
/**
* Checks that the completed future completed successfully.
*/
public static void checkSucceess(Future<?> future)
{
getDone(future);
}
/**
* Creates a future that completes when the first future completes either normally
* or exceptionally. Cancellation of the future propagates to the supplied futures.
*/
public static <V> ListenableFuture<V> whenAnyComplete(Iterable<? extends ListenableFuture<? extends V>> futures)
{
requireNonNull(futures, "futures is null");
checkArgument(!isEmpty(futures), "futures is empty");
ExtendedSettableFuture<V> firstCompletedFuture = ExtendedSettableFuture.create();
for (ListenableFuture<? extends V> future : futures) {
firstCompletedFuture.setAsync(future);
}
return firstCompletedFuture;
}
/**
* Creates a future that completes when the first future completes either normally
* or exceptionally. Cancellation of the future does not propagate to the supplied
* futures.
*/
public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures)
{
return firstCompletedFuture(futures, false);
}
/**
* Creates a future that completes when the first future completes either normally
* or exceptionally. Cancellation of the future will optionally propagate to the
* supplied futures.
*/
public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures, boolean propagateCancel)
{
requireNonNull(futures, "futures is null");
checkArgument(!isEmpty(futures), "futures is empty");
CompletableFuture<V> future = new CompletableFuture<>();
for (CompletionStage<? extends V> stage : futures) {
stage.whenComplete((value, exception) -> {
if (exception != null) {
future.completeExceptionally(exception);
}
else {
future.complete(value);
}
});
}
if (propagateCancel) {
future.exceptionally(throwable -> {
if (throwable instanceof CancellationException) {
for (CompletionStage<? extends V> sourceFuture : futures) {
if (sourceFuture instanceof Future) {
((Future<?>) sourceFuture).cancel(true);
}
}
}
return null;
});
}
return future;
}
/**
* Returns an unmodifiable future that is completed when all of the given
* futures complete. If any of the given futures complete exceptionally, then the
* returned future also does so immediately, with a CompletionException holding this exception
* as its cause. Otherwise, the results of the given futures are reflected in the
* returned future as a list of results matching the input order. If no futures are
* provided, returns a future completed with an empty list.
*/
public static <V> CompletableFuture<List<V>> allAsList(List<CompletableFuture<? extends V>> futures)
{
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
// Eagerly propagate exceptions, rather than waiting for all the futures to complete first (default behavior)
for (CompletableFuture<? extends V> future : futures) {
future.whenComplete((v, throwable) -> {
if (throwable != null) {
allDoneFuture.completeExceptionally(throwable);
}
});
}
return unmodifiableFuture(allDoneFuture.thenApply(v ->
futures.stream().
map(CompletableFuture::join).
collect(Collectors.<V>toList())));
}
/**
* Returns a new future that is completed when the supplied future completes or
* when the timeout expires. If the timeout occurs or the returned CompletableFuture
* is canceled, the supplied future will be canceled.
*/
public static <T> ListenableFuture<T> addTimeout(ListenableFuture<T> future, Callable<T> onTimeout, Duration timeout, ScheduledExecutorService executorService)
{
return catchingAsync(withTimeout(future, timeout.toMillis(), MILLISECONDS, executorService), TimeoutException.class, timeoutException -> {
try {
return immediateFuture(onTimeout.call());
}
catch (Throwable throwable) {
return immediateFailedFuture(throwable);
}
});
}
/**
* Returns a new future that is completed when the supplied future completes or
* when the timeout expires. If the timeout occurs or the returned CompletableFuture
* is canceled, the supplied future will be canceled.
*/
public static <T> CompletableFuture<T> addTimeout(CompletableFuture<T> future, Callable<T> onTimeout, Duration timeout, ScheduledExecutorService executorService)
{
requireNonNull(future, "future is null");
requireNonNull(onTimeout, "timeoutValue is null");
requireNonNull(timeout, "timeout is null");
requireNonNull(executorService, "executorService is null");
// if the future is already complete, just return it
if (future.isDone()) {
return future;
}
// create an unmodifiable future that propagates cancel
// down cast is safe because this is our code
UnmodifiableCompletableFuture<T> futureWithTimeout = (UnmodifiableCompletableFuture<T>) unmodifiableFuture(future, true);
// schedule a task to complete the future when the time expires
ScheduledFuture<?> timeoutTaskFuture = executorService.schedule(new TimeoutFutureTask<>(futureWithTimeout, onTimeout, future), timeout.toMillis(), MILLISECONDS);
// when future completes, cancel the timeout task
future.whenCompleteAsync((value, exception) -> timeoutTaskFuture.cancel(false), executorService);
return futureWithTimeout;
}
/**
* Converts a ListenableFuture to a CompletableFuture. Cancellation of the
* CompletableFuture will be propagated to the ListenableFuture.
*/
public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture)
{
requireNonNull(listenableFuture, "listenableFuture is null");
CompletableFuture<V> future = new CompletableFuture<>();
future.exceptionally(throwable -> {
if (throwable instanceof CancellationException) {
listenableFuture.cancel(true);
}
return null;
});
Futures.addCallback(listenableFuture, new FutureCallback<V>()
{
@Override
@SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
public void onSuccess(V result)
{
future.complete(result);
}
@Override
public void onFailure(Throwable t)
{
future.completeExceptionally(t);
}
});
return future;
}
/**
* Converts a CompletableFuture to a ListenableFuture. Cancellation of the
* ListenableFuture will be propagated to the CompletableFuture.
*/
public static <V> ListenableFuture<V> toListenableFuture(CompletableFuture<V> completableFuture)
{
requireNonNull(completableFuture, "completableFuture is null");
SettableFuture<V> future = SettableFuture.create();
propagateCancellation(future, completableFuture, true);
completableFuture.whenComplete((value, exception) -> {
if (exception != null) {
future.setException(exception);
}
else {
future.set(value);
}
});
return future;
}
public static <T> void addExceptionCallback(ListenableFuture<T> future, Consumer<Throwable> exceptionCallback)
{
requireNonNull(future, "future is null");
requireNonNull(exceptionCallback, "exceptionCallback is null");
Futures.addCallback(future, new FutureCallback<T>()
{
@Override
public void onSuccess(@Nullable T result)
{
}
@Override
public void onFailure(Throwable t)
{
exceptionCallback.accept(t);
}
});
}
public static <T> void addExceptionCallback(ListenableFuture<T> future, Runnable exceptionCallback)
{
requireNonNull(future, "future is null");
requireNonNull(exceptionCallback, "exceptionCallback is null");
Futures.addCallback(future, new FutureCallback<T>()
{
@Override
public void onSuccess(@Nullable T result)
{
}
@Override
public void onFailure(Throwable t)
{
exceptionCallback.run();
}
});
}
private static class UnmodifiableCompletableFuture<V>
extends CompletableFuture<V>
{
private final Function<Boolean, Boolean> onCancel;
public UnmodifiableCompletableFuture(Function<Boolean, Boolean> onCancel)
{
this.onCancel = requireNonNull(onCancel, "onCancel is null");
}
void internalComplete(V value)
{
super.complete(value);
}
void internalCompleteExceptionally(Throwable ex)
{
super.completeExceptionally(ex);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
return onCancel.apply(mayInterruptIfRunning);
}
@Override
public boolean complete(V value)
{
throw new UnsupportedOperationException();
}
@Override
public boolean completeExceptionally(Throwable ex)
{
if (ex instanceof CancellationException) {
return cancel(false);
}
throw new UnsupportedOperationException();
}
@Override
public void obtrudeValue(V value)
{
throw new UnsupportedOperationException();
}
@Override
public void obtrudeException(Throwable ex)
{
throw new UnsupportedOperationException();
}
}
private static class TimeoutFutureTask<T>
implements Runnable
{
private final UnmodifiableCompletableFuture<T> settableFuture;
private final Callable<T> timeoutValue;
private final WeakReference<CompletableFuture<T>> futureReference;
public TimeoutFutureTask(UnmodifiableCompletableFuture<T> settableFuture, Callable<T> timeoutValue, CompletableFuture<T> future)
{
this.settableFuture = settableFuture;
this.timeoutValue = timeoutValue;
// the scheduled executor can hold on to the timeout task for a long time, and
// the future can reference large expensive objects. Since we are only interested
// in canceling this future on a timeout, only hold a weak reference to the future
this.futureReference = new WeakReference<>(future);
}
@Override
public void run()
{
if (settableFuture.isDone()) {
return;
}
// run the timeout task and set the result into the future
try {
T result = timeoutValue.call();
settableFuture.internalComplete(result);
}
catch (Throwable t) {
settableFuture.internalCompleteExceptionally(t);
throwIfInstanceOf(t, RuntimeException.class);
}
// cancel the original future, if it still exists
Future<T> future = futureReference.get();
if (future != null) {
future.cancel(true);
}
}
}
}
|
package org.geojson;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import java.io.Serializable;
import java.util.Arrays;
@JsonTypeInfo(property = "type", use = Id.NAME)
@JsonSubTypes({ @Type(Feature.class), @Type(Polygon.class), @Type(MultiPolygon.class), @Type(FeatureCollection.class),
@Type(Point.class), @Type(MultiPoint.class), @Type(MultiLineString.class), @Type(LineString.class),
@Type(GeometryCollection.class) })
@JsonInclude(Include.NON_NULL)
public abstract class GeoJsonObject implements Serializable {
private Crs crs;
private double[] bbox;
public Crs getCrs() {
return crs;
}
public void setCrs(Crs crs) {
this.crs = crs;
}
public double[] getBbox() {
return bbox;
}
public void setBbox(double[] bbox) {
this.bbox = bbox;
}
public abstract <T> T accept(GeoJsonObjectVisitor<T> geoJsonObjectVisitor);
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GeoJsonObject that = (GeoJsonObject)o;
if (crs != null ? !crs.equals(that.crs) : that.crs != null)
return false;
return Arrays.equals(bbox, that.bbox);
}
@Override public int hashCode() {
int result = crs != null ? crs.hashCode() : 0;
result = 31 * result + (bbox != null ? Arrays.hashCode(bbox) : 0);
return result;
}
@Override
public String toString() {
return "GeoJsonObject{}";
}
}
|
package org.jpmml.xgboost;
import java.io.EOFException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.PMML;
import org.dmg.pmml.Visitor;
import org.dmg.pmml.mining.MiningModel;
import org.jpmml.converter.Feature;
import org.jpmml.converter.Label;
import org.jpmml.converter.Schema;
import org.jpmml.xgboost.visitors.TreeModelCompactor;
public class Learner {
private float base_score;
private int num_features;
private int num_class;
private int contain_extra_attrs;
private int contain_eval_metrics;
private ObjFunction obj;
private GBTree gbtree;
private Map<String, String> attributes = null;
private List<String> metrics = null;
public Learner(){
}
public void load(XGBoostDataInput input) throws IOException {
this.base_score = input.readFloat();
this.num_features = input.readInt();
this.num_class = input.readInt();
this.contain_extra_attrs = input.readInt();
this.contain_eval_metrics = input.readInt();
input.readReserved(29);
String name_obj = input.readString();
switch(name_obj){
case "reg:linear":
this.obj = new LinearRegression();
break;
case "reg:logistic":
this.obj = new LogisticRegression();
break;
case "reg:gamma":
case "reg:tweedie":
this.obj = new GeneralizedLinearRegression();
break;
case "count:poisson":
this.obj = new PoissonRegression();
break;
case "binary:logistic":
this.obj = new BinomialLogisticRegression();
break;
case "multi:softmax":
case "multi:softprob":
this.obj = new MultinomialLogisticRegression(this.num_class);
break;
default:
throw new IllegalArgumentException(name_obj);
}
String name_gbm = input.readString();
switch(name_gbm){
case "gbtree":
break;
default:
throw new IllegalArgumentException(name_gbm);
}
this.gbtree = new GBTree();
this.gbtree.load(input);
if(this.contain_extra_attrs != 0){
this.attributes = input.readStringMap();
} // End if
if(this.obj instanceof PoissonRegression){
String max_delta_step;
try {
max_delta_step = input.readString();
} catch(EOFException eof){
// Ignored
}
} // End if
if(this.contain_eval_metrics != 0){
this.metrics = input.readStringList();
}
}
public PMML encodePMML(FieldName targetField, List<String> targetCategories, FeatureMap featureMap, Map<String, ?> options){
XGBoostEncoder encoder = new XGBoostEncoder();
if(targetField == null){
targetField = FieldName.create("_target");
}
Label label = this.obj.encodeLabel(targetField, targetCategories, encoder);
List<Feature> features = featureMap.encodeFeatures(encoder);
Schema schema = new Schema(label, features);
MiningModel miningModel = encodeMiningModel(options, schema);
PMML pmml = encoder.encodePMML(miningModel);
return pmml;
}
/**
* @see XGBoostUtil#toXGBoostSchema(Schema)
*/
public MiningModel encodeMiningModel(Map<String, ?> options, Schema schema){
Boolean compact = (Boolean)options.get(HasXGBoostOptions.OPTION_COMPACT);
Integer ntreeLimit = (Integer)options.get(HasXGBoostOptions.OPTION_NTREE_LIMIT);
MiningModel miningModel = this.gbtree.encodeMiningModel(this.obj, this.base_score, ntreeLimit, schema)
.setAlgorithmName("XGBoost");
if((Boolean.TRUE).equals(compact)){
Visitor visitor = new TreeModelCompactor();
visitor.applyTo(miningModel);
}
return miningModel;
}
public float getBaseScore(){
return this.base_score;
}
public int getNumClass(){
return this.num_class;
}
public int getNumFeatures(){
return this.num_features;
}
public ObjFunction getObj(){
return this.obj;
}
public GBTree getGBTree(){
return this.gbtree;
}
}
|
package org.lantern;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
/**
* Base class for users of HttpURLConnetion that may use a proxy.
*/
public abstract class HttpURLClient {
private final Proxy proxy;
private volatile SSLContextSource sslContextSource;
protected HttpURLClient() {
this(null);
}
protected HttpURLClient(InetSocketAddress proxyAddress) {
if (proxyAddress != null) {
this.proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
} else {
this.proxy = null;
}
}
public void setSslContextSource(SSLContextSource sslContextSource) {
this.sslContextSource = sslContextSource;
}
protected HttpURLConnection newConn(String url) throws IOException {
final HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection(proxy == null ? Proxy.NO_PROXY : proxy);
conn.setConnectTimeout(50000);
conn.setReadTimeout(120000);
boolean useCustomSslContext = sslContextSource != null;
boolean isSSL = conn instanceof HttpsURLConnection;
if (isSSL && useCustomSslContext) {
SSLContext sslContext = sslContextSource.getContext(url);
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
SSLSocketFactory sf =
new NoSSLv2SocketFactory(sslContext.getSocketFactory());
httpsConn.setSSLSocketFactory(sf);
}
return conn;
}
public interface SSLContextSource {
SSLContext getContext(String url);
}
}
|
package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.AddVdsActionParameters;
import org.ovirt.engine.core.common.action.ApproveVdsParameters;
import org.ovirt.engine.core.common.action.UpdateVdsActionParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VDSType;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.queries.RegisterVdsParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.Regex;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.dao.VdsDAO;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
@DisableInMaintenanceMode
public class RegisterVdsQuery<P extends RegisterVdsParameters> extends QueriesCommandBase<P> {
private AuditLogType error = AuditLogType.UNASSIGNED;
private String strippedVdsUniqueId;
private final AuditLogableBase logable;
private List<VDS> _vdssByUniqueId;
private static Object doubleRegistrationLock = new Object();
/**
* 'z' has the highest ascii value from the acceptable characters, so the bit set size should be initiated to it.
* the size is 'z'+1 so that each char will be represented in the BitSet with index which equals to it's char value.
*/
private static final BitSet validChars = new BitSet('z' + 1);
static {
// the set method sets the bits from the specified from index(inclusive) to the specified toIndex(exclusive) to
// true so the toIndex should be incremented in 1 in order to include the char represented by that index in the
// range.
validChars.set('a', 'z' + 1);
validChars.set('A', 'Z' + 1);
validChars.set('0', '9' + 1);
validChars.set('-');
validChars.set('.');
validChars.set(':');
validChars.set('_');
}
public RegisterVdsQuery(P parameters) {
super(parameters);
logable = new AuditLogableBase(parameters.getVdsId());
}
protected String getStrippedVdsUniqueId() {
if (strippedVdsUniqueId == null) {
// since we use the management IP field, makes sense to remove the
StringBuilder builder = new StringBuilder();
for (char ch : getParameters().getVdsUniqueId().toCharArray()) {
if (validChars.get(ch)) {
builder.append(ch);
}
}
strippedVdsUniqueId = builder.toString();
}
return strippedVdsUniqueId;
}
private List<VDS> getVdssByUniqueId() {
if (_vdssByUniqueId == null) {
_vdssByUniqueId = DbFacade.getInstance().getVdsDao().getAllWithUniqueId(getStrippedVdsUniqueId());
}
return _vdssByUniqueId;
}
@Override
protected boolean validateInputs() {
if (!super.validateInputs()) {
return false;
}
VdcQueryReturnValue returnValue = getQueryReturnValue();
returnValue.setExceptionString("");
try {
String hostName = getParameters().getVdsHostName();
if (StringUtils.isEmpty(hostName)) {
returnValue.setExceptionString("Cannot register Host - no Hostname address specified.");
return false;
}
String vdsUniqueId = getParameters().getVdsUniqueId();
if (StringUtils.isEmpty(vdsUniqueId)) {
returnValue.setExceptionString(
String.format(
"Cannot register host '%1$s' - host id is empty.",
hostName
)
);
AuditLogableBase logable = new AuditLogableBase();
logable.addCustomValue("VdsHostName", hostName);
AuditLogDirector.log(logable, AuditLogType.VDS_REGISTER_EMPTY_ID);
return false;
}
List<VDS> vdssByUniqueId = getVdssByUniqueId();
if (vdssByUniqueId.size() > 1) {
returnValue.setExceptionString("Cannot register Host - unique id is ambigious.");
return false;
}
if (vdssByUniqueId.size() == 1) {
VDS vds = vdssByUniqueId.get(0);
if (!VdsHandler.isPendingOvirt(vds)) {
returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name());
return false;
}
}
} catch (RuntimeException ex) {
log.error("Exception", ex);
returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s",
ex.getMessage()));
return false;
}
return true;
}
@Override
protected void executeQueryCommand() {
try {
log.info("Running Command: RegisterVds");
executeRegisterVdsCommand();
} catch (RuntimeException ex) {
log.error("RegisterVdsQuery::ExecuteWithoutTransaction: An exception has been thrown.", ex);
} finally {
writeToAuditLog();
}
}
protected void executeRegisterVdsCommand() {
synchronized (doubleRegistrationLock) {
// force to reload vdss by unique ID used later on
_vdssByUniqueId = null;
VDS vdsByUniqueId = getVdssByUniqueId().size() != 0 ? getVdssByUniqueId().get(0) : null;
VDS provisionedVds = DbFacade.getInstance().getVdsDao().getByName(getParameters().getVdsName());
if (provisionedVds != null && provisionedVds.getStatus() != VDSStatus.InstallingOS) {
// if not in InstallingOS status, this host is not provisioned.
provisionedVds = null;
}
// in case oVirt host was added for the second time - perform approval
if (vdsByUniqueId != null && vdsByUniqueId.getStatus() == VDSStatus.PendingApproval) {
getQueryReturnValue().setSucceeded(dispatchOvirtApprovalCommand(vdsByUniqueId.getId()));
return;
}
log.debug("RegisterVdsQuery::ExecuteCommand - Entering");
if (StringUtils.isEmpty(getParameters().getVdsName())) {
getParameters().setVdsName(getParameters().getVdsUniqueId());
log.debug("RegisterVdsQuery::ExecuteCommand - VdsName empty, using VdsUnique ID as name");
}
logable.addCustomValue("VdsName1", getParameters().getVdsName());
Guid vdsGroupId;
if (Guid.Empty.equals(getParameters().getVdsGroupId())) {
vdsGroupId = Guid.createGuidFromStringDefaultEmpty(
Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID));
log.debug(
"RegisterVdsQuery::ExecuteCommand - VdsGroupId received as -1, using AutoRegistrationDefaultVdsGroupID: '{}'",
vdsGroupId);
} else {
vdsGroupId = getParameters().getVdsGroupId();
}
if (provisionedVds != null) {
getQueryReturnValue().setSucceeded(Register(provisionedVds, vdsGroupId, false));
} else {
// TODO: always add in pending state, and if auto approve call
// approve command action after registration
RefObject<Boolean> isPending = new RefObject<Boolean>(Boolean.FALSE);
getQueryReturnValue().setSucceeded(
HandleOldVdssWithSameHostName(vdsByUniqueId) && HandleOldVdssWithSameName(vdsByUniqueId)
&& CheckAutoApprovalDefinitions(isPending)
&& Register(vdsByUniqueId, vdsGroupId, isPending.argvalue.booleanValue()));
}
log.debug("RegisterVdsQuery::ExecuteCommand - Leaving Succeded value is '{}'",
getQueryReturnValue().getSucceeded());
}
}
private boolean dispatchOvirtApprovalCommand(Guid oVirtId) {
boolean isApprovalDispatched = true;
final ApproveVdsParameters params = new ApproveVdsParameters();
params.setVdsId(oVirtId);
params.setApprovedByRegister(true);
try {
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
try {
VdcReturnValueBase ret =
Backend.getInstance().runInternalAction(VdcActionType.ApproveVds, params);
if (ret == null || !ret.getSucceeded()) {
log.error("Approval of oVirt '{}' failed. ", params.getVdsId());
} else if (ret.getSucceeded()) {
log.info("Approval of oVirt '{}' ended successfully. ", params.getVdsId());
}
} catch (RuntimeException ex) {
log.error("Failed to Approve host", ex);
}
}
});
} catch (Exception e) {
isApprovalDispatched = false;
}
return isApprovalDispatched;
}
private boolean Register(VDS vds, Guid vdsGroupId, boolean IsPending) {
boolean returnValue = true;
log.debug("RegisterVdsQuery::Register - Entering");
if (vds == null) {
returnValue = registerNewHost(vdsGroupId, IsPending);
} else {
returnValue = updateExistingHost(vds, IsPending);
}
log.debug("RegisterVdsQuery::Register - Leaving with value {}", returnValue);
return returnValue;
}
private boolean updateExistingHost(VDS vdsByUniqueId, boolean IsPending) {
boolean returnValue = true;
vdsByUniqueId.setHostName(getParameters().getVdsHostName());
vdsByUniqueId.setPort(getParameters().getVdsPort());
log.debug(
"RegisterVdsQuery::Register - Will try now to update VDS with existing unique id; Name: '{}', Hostname: '{}', Unique: '{}', VdsPort: '{}', IsPending: '{}' with force synchronize",
getParameters().getVdsHostName(),
getStrippedVdsUniqueId(),
getStrippedVdsUniqueId(),
getParameters().getVdsPort(),
IsPending);
UpdateVdsActionParameters p = new UpdateVdsActionParameters(vdsByUniqueId.getStaticData(), "", false);
p.setTransactionScopeOption(TransactionScopeOption.RequiresNew);
VdcReturnValueBase rc = Backend.getInstance().runInternalAction(VdcActionType.UpdateVds, p);
if (rc == null || !rc.getSucceeded()) {
error = AuditLogType.VDS_REGISTER_EXISTING_VDS_UPDATE_FAILED;
log.debug(
"RegisterVdsQuery::Register - Failed to update existing VDS Name: '{}', Hostname: '{}', Unique: '{}', VdsPort: '{}', IsPending: '{}'",
getParameters().getVdsHostName(),
getStrippedVdsUniqueId(),
getStrippedVdsUniqueId(),
getParameters().getVdsPort(),
IsPending);
CaptureCommandErrorsToLogger(rc, "RegisterVdsQuery::Register");
returnValue = false;
} else {
log.info(
"RegisterVdsQuery::Register - Updated a '{}' registered VDS - Name: '{}', Hostname: '{}', UniqueID: '{}'",
vdsByUniqueId.getStatus() == VDSStatus.PendingApproval ? "Pending " : "",
getParameters().getVdsName(),
getParameters().getVdsHostName(),
getStrippedVdsUniqueId());
}
return returnValue;
}
private boolean registerNewHost(Guid vdsGroupId, boolean IsPending) {
boolean returnValue = true;
VdsStatic vds = new VdsStatic(getParameters().getVdsHostName(), "",
getStrippedVdsUniqueId(), getParameters().getVdsPort(),
getParameters().getSSHPort(),
getParameters().getSSHUser(),
vdsGroupId, Guid.Empty,
getParameters().getVdsName(), Config.<Boolean> getValue(ConfigValues.SSLEnabled),
VDSType.VDS, null);
vds.setSshKeyFingerprint(getParameters().getSSHFingerprint());
log.debug(
"RegisterVdsQuery::Register - Will try now to add VDS from scratch; Name: '{}', Hostname: '{}', Unique: '{}', VdsPort: '{}',Subnet mask: '{}', IsPending: '{}' with force synchronize",
getParameters().getVdsName(),
getParameters().getVdsHostName(),
getStrippedVdsUniqueId(),
getParameters().getVdsPort(),
IsPending);
AddVdsActionParameters p = new AddVdsActionParameters(vds, "");
p.setAddPending(IsPending);
VdcReturnValueBase ret = Backend.getInstance().runInternalAction(VdcActionType.AddVds, p);
if (ret == null || !ret.getSucceeded()) {
log.error(
"RegisterVdsQuery::Register - Registration failed for VDS - Name: '{}', Hostname: '{}', UniqueID: '{}', Subnet mask: '{}'",
getParameters().getVdsName(),
getParameters().getVdsHostName(),
getStrippedVdsUniqueId());
CaptureCommandErrorsToLogger(ret, "RegisterVdsQuery::Register");
error = AuditLogType.VDS_REGISTER_FAILED;
returnValue = false;
} else {
log.info(
"RegisterVdsQuery::Register - Registered a new VDS '{}' - Name: '{}', Hostname: '{}', UniqueID: '{}'",
IsPending ? "pending approval" : "automatically approved",
getParameters().getVdsName(),
getParameters().getVdsHostName(),
getStrippedVdsUniqueId());
}
return returnValue;
}
private boolean HandleOldVdssWithSameHostName(VDS vdsByUniqueId) {
// handle old VDSs with same host_name (IP)
log.debug("RegisterVdsQuery::HandleOldVdssWithSameHostName - Entering");
boolean returnValue = true;
List<VDS> vdss_byHostName = DbFacade.getInstance().getVdsDao().getAllForHostname(
getParameters().getVdsHostName());
int lastIteratedIndex = 1;
if (vdss_byHostName.size() > 0) {
log.debug(
"RegisterVdsQuery::HandleOldVdssWithSameHostName - found '{}' VDS(s) with the same host name '{}'. Will try to change their hostname to a different value",
vdss_byHostName.size(),
getParameters().getVdsHostName());
for (VDS vds_byHostName : vdss_byHostName) {
/**
* looping foreach VDS found with similar hostnames and change to each one to available hostname
*/
if (
vdsByUniqueId == null ||
!vds_byHostName.getId().equals(vdsByUniqueId.getId())
) {
boolean unique = false;
String try_host_name = "";
for (int i = lastIteratedIndex; i <= 100; i++, lastIteratedIndex = i) {
try_host_name = String.format("hostname-was-%1$s-%2$s", getParameters()
.getVdsHostName(), i);
if (DbFacade.getInstance().getVdsDao().getAllForHostname(try_host_name).size() == 0) {
unique = true;
break;
}
}
if (unique) {
String old_host_name = vds_byHostName.getHostName();
vds_byHostName.setHostName(try_host_name);
UpdateVdsActionParameters parameters = new UpdateVdsActionParameters(
vds_byHostName.getStaticData(), "" , false);
parameters.setShouldBeLogged(false);
parameters.setTransactionScopeOption(TransactionScopeOption.RequiresNew);
// If host exists in InstallingOs status, remove it from DB and move on
final VDS foundVds = DbFacade.getInstance().getVdsDao().getByName(parameters.getVdsStaticData().getName());
if ((foundVds != null) && (foundVds.getDynamicData().getStatus() == VDSStatus.InstallingOS)) {
TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
getDbFacade().getVdsStatisticsDao().remove(foundVds.getId());
getDbFacade().getVdsDynamicDao().remove(foundVds.getId());
getDbFacade().getVdsStaticDao().remove(foundVds.getId());
return null;
}
});
}
VdcReturnValueBase ret = Backend.getInstance().runInternalAction(VdcActionType.UpdateVds, parameters);
if (ret == null || !ret.getSucceeded()) {
error = AuditLogType.VDS_REGISTER_ERROR_UPDATING_HOST;
logable.addCustomValue("VdsName2", vds_byHostName.getStaticData().getName());
log.error(
"RegisterVdsQuery::HandleOldVdssWithSameHostName - could not update VDS '{}'",
vds_byHostName.getStaticData().getName());
CaptureCommandErrorsToLogger(ret,
"RegisterVdsQuery::HandleOldVdssWithSameHostName");
return false;
} else {
log.info(
"RegisterVdsQuery::HandleOldVdssWithSameHostName - Another VDS was using this IP '{}'. Changed to '{}'",
old_host_name,
try_host_name);
}
} else {
log.error(
"VdcBLL::HandleOldVdssWithSameHostName - Could not change the IP for an existing VDS. All available hostnames are taken (ID = '{}', name = '{}', management IP = '{}' , host name = '{}')",
vds_byHostName.getId(),
vds_byHostName.getName(),
vds_byHostName.getManagementIp(),
vds_byHostName.getHostName());
error = AuditLogType.VDS_REGISTER_ERROR_UPDATING_HOST_ALL_TAKEN;
returnValue = false;
}
}
log.info(
"RegisterVdsQuery::HandleOldVdssWithSameHostName - No Change required for VDS '{}'. Since it has the same unique Id",
vds_byHostName.getId());
}
}
log.debug("RegisterVdsQuery::HandleOldVdssWithSameHostName - Leaving with value '{}'", returnValue);
return returnValue;
}
/**
* Check if another host has the same name as hostToRegister and if yes append a number to it. Eventually if the
* host is in the db, persist the changes.
* @param hostToRegister
* @return
*/
private boolean HandleOldVdssWithSameName(VDS hostToRegister) {
log.debug("Entering");
boolean returnValue = true;
VdsDAO vdsDAO = DbFacade.getInstance().getVdsDao();
VDS storedHost = vdsDAO.getByName(getParameters().getVdsName());
List<String> allHostNames = getAllHostNames(vdsDAO.getAll());
boolean hostExistInDB = hostToRegister != null;
if (storedHost != null) {
log.debug(
"found VDS with the same name {0}. Will try to register with a new name",
getParameters().getVdsName());
String nameToRegister = getParameters().getVdsName();
String uniqueIdToRegister = getParameters().getVdsUniqueId();
String newName;
// check different uniqueIds but same name
if (!uniqueIdToRegister.equals(storedHost.getUniqueId())
&& nameToRegister.equals(storedHost.getName())) {
if (hostExistInDB) {
// update the registered host if exist in db
allHostNames.remove(hostToRegister.getName());
newName = generateUniqueName(nameToRegister, allHostNames);
hostToRegister.setVdsName(newName);
UpdateVdsActionParameters parameters =
new UpdateVdsActionParameters(hostToRegister.getStaticData(), "", false);
VdcReturnValueBase ret = Backend.getInstance().runInternalAction(VdcActionType.UpdateVds, parameters);
if (ret == null || !ret.getSucceeded()) {
error = AuditLogType.VDS_REGISTER_ERROR_UPDATING_NAME;
logable.addCustomValue("VdsName2", newName);
log.error("could not update VDS '{}'", nameToRegister);
CaptureCommandErrorsToLogger(ret, "RegisterVdsQuery::HandleOldVdssWithSameName");
return false;
} else {
log.info(
"Another VDS was using this name with IP '{}'. Changed to '{}'",
nameToRegister,
newName);
}
} else {
// host doesn't exist in db yet. not persisting changes just object values.
newName = generateUniqueName(nameToRegister, allHostNames);
getParameters().setVdsName(newName);
}
}
}
log.debug("Leaving with value '{}'", returnValue);
return returnValue;
}
private List<String> getAllHostNames(List<VDS> allHosts) {
List<String> allHostNames = new ArrayList<String>(allHosts.size());
for (VDS vds : allHosts) {
allHostNames.add(vds.getName());
}
return allHostNames;
}
private String generateUniqueName(String val, List<String> allHostNames) {
int i = 2;
boolean postfixed = false;
StringBuilder sb = new StringBuilder(val);
while (allHostNames.contains(val)) {
if (!postfixed) {
val = sb.append("-").append(i).toString();
postfixed = true;
} else {
val = sb.replace(sb.lastIndexOf("-"), sb.length(), "-").append(i).toString();
}
i++;
}
return val;
}
private boolean CheckAutoApprovalDefinitions(RefObject<Boolean> isPending) {
// check auto approval definitions
log.debug("RegisterVdsQuery::CheckAutoApprovalDefinitions - Entering");
isPending.argvalue = true;
if (!Config.<String> getValue(ConfigValues.AutoApprovePatterns).equals("")) {
for (String pattern : Config.<String> getValue(ConfigValues.AutoApprovePatterns)
.split("[,]", -1)) {
try {
String pattern_helper = pattern.toLowerCase();
Regex pattern_regex = new Regex(pattern_helper);
String vds_hostname_helper = getParameters().getVdsHostName().toLowerCase();
String vds_unique_id_helper = getParameters().getVdsUniqueId().toLowerCase()
.replace(":", "-");
if (vds_hostname_helper.startsWith(pattern) || vds_unique_id_helper.startsWith(pattern)
|| pattern_regex.IsMatch(vds_hostname_helper)
|| pattern_regex.IsMatch(vds_unique_id_helper)) {
isPending.argvalue = false;
break;
}
} catch (RuntimeException ex) {
error = AuditLogType.VDS_REGISTER_AUTO_APPROVE_PATTERN;
log.error(
"RegisterVdsQuery ::CheckAutoApprovalDefinitions(out bool) - Error in auto approve pattern: '{}'-'{}'",
pattern,
ex.getMessage());
return false;
}
}
}
log.debug("RegisterVdsQuery::CheckAutoApprovalDefinitions - Leaving - return value '{}'",
isPending.argvalue);
return true;
}
private void CaptureCommandErrorsToLogger(VdcReturnValueBase retValue, String prefixToMessage) {
if (retValue.getFault() != null) {
log.error("{} - Fault - {}", prefixToMessage, retValue.getFault().getMessage());
}
if (retValue.getCanDoActionMessages().size() > 0) {
List<String> msgs = retValue.getCanDoActionMessages();
for (String s : msgs) {
log.error("{} - CanDoAction Fault - {}", prefixToMessage, s);
}
}
if (retValue.getExecuteFailedMessages().size() > 0) {
// List<string> msgs =
// ErrorTranslator.TranslateErrorText(retValue.ExecuteFailedMessages);
for (String s : retValue.getExecuteFailedMessages()) {
log.error("{} - Ececution Fault - {}", prefixToMessage, s);
}
}
}
private void writeToAuditLog() {
try {
AuditLogDirector.log(logable, getAuditLogTypeValue());
} catch (RuntimeException ex) {
log.error("RegisterVdsQuery::WriteToAuditLog: An exception has been thrown.", ex);
}
}
protected AuditLogType getAuditLogTypeValue() {
return getQueryReturnValue().getSucceeded() ? AuditLogType.VDS_REGISTER_SUCCEEDED : error;
}
}
|
package org.nerdpower.tabula;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
// TODO: this class should probably be called "PageArea" or something like that
public class Page extends Rectangle {
private Integer rotation;
private int pageNumber;
private List<TextElement> texts;
private List<Ruling> rulings, cleanRulings = null, verticalRulingLines = null, horizontalRulingLines = null;
private float minCharWidth;
private float minCharHeight;
private RectangleSpatialIndex<TextElement> spatial_index;
public Page(float top, float left, float width, float height, int rotation, int page_number) {
super(top, left, width, height);
this.rotation = rotation;
this.pageNumber = page_number;
}
public Page(float top, float left, float width, float height, int rotation, int page_number,
List<TextElement> characters, List<Ruling> rulings) {
this(top, left, width, height, rotation, page_number);
this.texts = characters;
this.rulings = rulings;
}
public Page(float top, float left, float width, float height, int rotation, int page_number,
List<TextElement> characters, List<Ruling> rulings,
float minCharWidth, float minCharHeight, RectangleSpatialIndex<TextElement> index) {
this(top, left, width, height, rotation, page_number, characters, rulings);
this.minCharHeight = minCharHeight;
this.minCharWidth = minCharWidth;
this.spatial_index = index;
}
public Page getArea(Rectangle area) {
List<TextElement> t = getText(area);
Page rv = new Page(
(float) area.getTop(),
(float) area.getLeft(),
(float) area.getWidth(),
(float) area.getHeight(),
rotation,
pageNumber,
t,
Ruling.cropRulingsToArea(getRulings(), area),
Collections.min(t, new Comparator<TextElement>() {
@Override
public int compare(TextElement te1, TextElement te2) {
return java.lang.Float.compare(te1.width, te2.width);
}}).width,
Collections.min(t, new Comparator<TextElement>() {
@Override
public int compare(TextElement te1, TextElement te2) {
return java.lang.Float.compare(te1.height, te2.height);
}}).height,
spatial_index);
return rv;
}
public Page getArea(float top, float left, float bottom, float right) {
Rectangle area = new Rectangle(top, left, right - left, bottom - top);
return this.getArea(area);
}
public List<TextElement> getText() {
return texts;
}
public List<TextElement> getText(Rectangle area) {
return this.spatial_index.contains(area);
}
public List<TextElement> getText(float top, float left, float bottom, float right) {
return this.getText(new Rectangle(top, left, right - left, bottom - top));
}
public Integer getRotation() {
return rotation;
}
public int getPageNumber() {
return pageNumber;
}
public List<TextElement> getTexts() {
return texts;
}
/**
* Returns the minimum bounding box that contains all the TextElements on this Page
* @return
*/
public Rectangle getTextBounds() {
List<TextElement> texts = this.getText();
if (!texts.isEmpty()) {
return Utils.bounds(texts);
}
else {
return new Rectangle();
}
}
public List<Ruling> getRulings() {
if (this.cleanRulings != null) {
return this.cleanRulings;
}
if (this.rulings == null || this.rulings.isEmpty()) {
this.verticalRulingLines = new ArrayList<Ruling>();
this.horizontalRulingLines = new ArrayList<Ruling>();
return new ArrayList<Ruling>();
}
this.snapPoints();
List<Ruling> vrs = new ArrayList<Ruling>();
for (Ruling vr: this.rulings) {
if (vr.vertical()) {
vrs.add(vr);
}
}
this.verticalRulingLines = Ruling.collapseOrientedRulings(vrs);
List<Ruling> hrs = new ArrayList<Ruling>();
for (Ruling hr: this.rulings) {
if (hr.horizontal()) {
hrs.add(hr);
}
}
this.horizontalRulingLines = Ruling.collapseOrientedRulings(hrs);
this.cleanRulings = new ArrayList<Ruling>(this.verticalRulingLines);
this.cleanRulings.addAll(this.horizontalRulingLines);
return this.cleanRulings;
}
public List<Ruling> getVerticalRulings() {
if (this.verticalRulingLines != null) {
return this.verticalRulingLines;
}
this.getRulings();
return this.verticalRulingLines;
}
public List<Ruling> getHorizontalRulings() {
if (this.horizontalRulingLines != null) {
return this.horizontalRulingLines;
}
this.getRulings();
return this.horizontalRulingLines;
}
public void addRuling(Ruling r) {
if (r.oblique()) {
throw new UnsupportedOperationException("Can't add a non horizontal ruling");
}
this.rulings.add(r);
// clear caches
this.verticalRulingLines = null;
this.horizontalRulingLines = null;
this.cleanRulings = null;
}
public List<Ruling> getUnprocessedRulings() {
return this.rulings;
}
public float getMinCharWidth() {
return minCharWidth;
}
public float getMinCharHeight() {
return minCharHeight;
}
public RectangleSpatialIndex<TextElement> getSpatialIndex() {
return this.spatial_index;
}
public boolean hasTexts() {
return this.texts.size() > 0;
}
public void snapPoints() {
// collect points and keep a Line -> p1,p2 map
Map<Ruling, Point2D[]> linesToPoints = new HashMap<Ruling, Point2D[]>();
List<Point2D> points = new ArrayList<Point2D>();
for (Ruling r: this.rulings) {
Point2D p1 = r.getP1();
Point2D p2 = r.getP2();
linesToPoints.put(r, new Point2D[] { p1, p2 });
points.add(p1);
points.add(p2);
}
// snap by X
Collections.sort(points, new Comparator<Point2D>() {
@Override
public int compare(Point2D arg0, Point2D arg1) {
return java.lang.Double.compare(arg0.getX(), arg1.getX());
}
});
List<List<Point2D>> groupedPoints = new ArrayList<List<Point2D>>();
groupedPoints.add(new ArrayList<Point2D>(Arrays.asList(new Point2D[] { points.get(0) })));
for (Point2D p: points.subList(1, points.size() - 1)) {
List<Point2D> last = groupedPoints.get(groupedPoints.size() - 1);
if (Math.abs(p.getX() - last.get(0).getX()) < this.minCharWidth) {
groupedPoints.get(groupedPoints.size() - 1).add(p);
}
else {
groupedPoints.add(new ArrayList<Point2D>(Arrays.asList(new Point2D[] { p })));
}
}
for(List<Point2D> group: groupedPoints) {
float avgLoc = 0;
for(Point2D p: group) {
avgLoc += p.getX();
}
avgLoc /= group.size();
for(Point2D p: group) {
p.setLocation(avgLoc, p.getY());
}
}
// snap by Y
Collections.sort(points, new Comparator<Point2D>() {
@Override
public int compare(Point2D arg0, Point2D arg1) {
return java.lang.Double.compare(arg0.getY(), arg1.getY());
}
});
groupedPoints = new ArrayList<List<Point2D>>();
groupedPoints.add(new ArrayList<Point2D>(Arrays.asList(new Point2D[] { points.get(0) })));
for (Point2D p: points.subList(1, points.size() - 1)) {
List<Point2D> last = groupedPoints.get(groupedPoints.size() - 1);
if (Math.abs(p.getY() - last.get(0).getY()) < this.minCharHeight) {
groupedPoints.get(groupedPoints.size() - 1).add(p);
}
else {
groupedPoints.add(new ArrayList<Point2D>(Arrays.asList(new Point2D[] { p })));
}
}
for(List<Point2D> group: groupedPoints) {
float avgLoc = 0;
for(Point2D p: group) {
avgLoc += p.getY();
}
avgLoc /= group.size();
for(Point2D p: group) {
p.setLocation(p.getX(), avgLoc);
}
}
// finally, modify lines
for(Map.Entry<Ruling, Point2D[]> ltp: linesToPoints.entrySet()) {
Point2D[] p = ltp.getValue();
ltp.getKey().setLine(p[0], p[1]);
}
}
}
|
package org.ovirt.engine.core.bll;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator;
import org.ovirt.engine.core.common.action.AddVmFromSnapshotParameters;
import org.ovirt.engine.core.common.action.AddVmParameters;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.GraphicsDevice;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend;
import org.ovirt.engine.core.common.osinfo.OsRepository;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.utils.SimpleDependecyInjector;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskImageDao;
import org.ovirt.engine.core.dao.SnapshotDao;
import org.ovirt.engine.core.dao.StorageDomainDao;
import org.ovirt.engine.core.dao.VdsGroupDao;
import org.ovirt.engine.core.dao.VmDao;
import org.ovirt.engine.core.dao.VmDeviceDao;
import org.ovirt.engine.core.dao.VmTemplateDao;
import org.ovirt.engine.core.utils.MockConfigRule;
@SuppressWarnings("serial")
public class AddVmCommandTest extends BaseCommandTest {
private static final Guid STORAGE_DOMAIN_ID_1 = Guid.newGuid();
private static final Guid STORAGE_DOMAIN_ID_2 = Guid.newGuid();
protected static final int TOTAL_NUM_DOMAINS = 2;
private static final int NUM_DISKS_STORAGE_DOMAIN_1 = 3;
private static final int NUM_DISKS_STORAGE_DOMAIN_2 = 3;
private static final int REQUIRED_DISK_SIZE_GB = 10;
private static final int AVAILABLE_SPACE_GB = 11;
private static final int USED_SPACE_GB = 4;
private static final int MAX_PCI_SLOTS = 26;
private static final Guid STORAGE_POOL_ID = Guid.newGuid();
private static final String CPU_ID = "0";
private VmTemplate vmTemplate;
private VDSGroup vdsGroup;
private StoragePool storagePool;
protected StorageDomainValidator storageDomainValidator;
private static final Map<String, String> migrationMap = new HashMap<>();
static {
migrationMap.put("undefined", "true");
migrationMap.put("x86_64", "true");
migrationMap.put("ppc64", "false");
}
@Rule
public MockConfigRule mcr = new MockConfigRule();
@Rule
public InjectorRule injectorRule = new InjectorRule();
@Mock
StorageDomainDao sdDao;
@Mock
VmTemplateDao vmTemplateDao;
@Mock
VmDao vmDao;
@Mock
DiskImageDao diskImageDao;
@Mock
VdsGroupDao vdsGroupDao;
@Mock
BackendInternal backend;
@Mock
VDSBrokerFrontend vdsBrokerFrontend;
@Mock
SnapshotDao snapshotDao;
@Mock
CpuFlagsManagerHandler cpuFlagsManagerHandler;
@Mock
OsRepository osRepository;
@Mock
VmDeviceDao deviceDao;
@Mock
DbFacade dbFacade;
@Before
public void InitTest() {
mockCpuFlagsManagerHandler();
mockOsRepository();
SimpleDependecyInjector.getInstance().bind(DbFacade.class, dbFacade);
}
@Test
public void create10GBVmWith11GbAvailableAndA5GbBuffer() throws Exception {
VM vm = createVm();
AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm);
mockStorageDomainDaoGetForStoragePool();
mockVdsGroupDaoReturnVdsGroup();
mockVmTemplateDaoReturnVmTemplate();
mockDiskImageDaoGetSnapshotById();
mockVerifyAddVM(cmd);
mockConfig();
mockMaxPciSlots();
mockOsRepository();
mockOsRepositoryGraphics(0, Version.v3_3, new Pair<>(GraphicsType.SPICE, DisplayType.qxl));
mockGraphicsDevices(vm.getId());
mockStorageDomainDaoGetAllStoragesForPool(AVAILABLE_SPACE_GB);
mockUninterestingMethods(cmd);
mockGetAllSnapshots(cmd);
doReturn(createStoragePool()).when(cmd).getStoragePool();
CanDoActionTestUtils.runAndAssertCanDoActionFailure
(cmd, EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN);
}
private void mockGraphicsDevices(Guid vmId) {
VmDevice graphicsDevice = new GraphicsDevice(VmDeviceType.SPICE);
graphicsDevice.setDeviceId(Guid.Empty);
graphicsDevice.setVmId(vmId);
when(deviceDao.getVmDeviceByVmIdAndType(vmId, VmDeviceGeneralType.GRAPHICS)).thenReturn(Collections.singletonList(graphicsDevice));
doReturn(deviceDao).when(dbFacade).getVmDeviceDao();
}
private void mockOsRepositoryGraphics(int osId, Version ver, Pair<GraphicsType, DisplayType> supportedGraphicsAndDisplay) {
Map<Version, List<Pair<GraphicsType, DisplayType>>> value = new HashMap<>();
value.put(ver, Collections.singletonList(supportedGraphicsAndDisplay));
Map<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> g = new HashMap<>();
g.put(osId, value);
when(osRepository.getGraphicsAndDisplays()).thenReturn(g);
}
protected void mockCpuFlagsManagerHandler() {
injectorRule.bind(CpuFlagsManagerHandler.class, cpuFlagsManagerHandler);
when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID);
}
protected void mockOsRepository() {
SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);
VmHandler.init();
when(osRepository.isWindows(0)).thenReturn(true);
when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true);
}
@Test
public void canAddVm() {
ArrayList<String> reasons = new ArrayList<>();
final int domainSizeGB = 20;
AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB);
cmd.postConstruct();
doReturn(true).when(cmd).validateCustomProperties(any(VmStatic.class), anyList());
doReturn(true).when(cmd).validateSpaceRequirements();
assertTrue("vm could not be added", cmd.canAddVm(reasons, Collections.singletonList(createStorageDomain(domainSizeGB))));
}
@Test
public void canAddCloneVmFromSnapshotSnapshotDoesNotExist() {
final int domainSizeGB = 15;
final Guid sourceSnapshotId = Guid.newGuid();
AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd =
setupCanAddVmFromSnapshotTests(domainSizeGB, sourceSnapshotId);
cmd.getVm().setName("vm1");
mockNonInterestingMethodsForCloneVmFromSnapshot(cmd);
CanDoActionTestUtils.runAndAssertCanDoActionFailure
(cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST);
}
@Test
public void canAddCloneVmFromSnapshotNoConfiguration() {
final int domainSizeGB = 15;
final Guid sourceSnapshotId = Guid.newGuid();
AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd =
setupCanAddVmFromSnapshotTests(domainSizeGB, sourceSnapshotId);
cmd.getVm().setName("vm1");
mockNonInterestingMethodsForCloneVmFromSnapshot(cmd);
SnapshotsValidator sv = spy(new SnapshotsValidator());
doReturn(ValidationResult.VALID).when(sv).vmNotDuringSnapshot(any(Guid.class));
doReturn(sv).when(cmd).createSnapshotsValidator();
when(snapshotDao.get(sourceSnapshotId)).thenReturn(new Snapshot());
CanDoActionTestUtils.runAndAssertCanDoActionFailure
(cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_HAS_NO_CONFIGURATION);
}
@Test
public void canAddVmWithVirtioScsiControllerNotSupportedOs() {
VM vm = createVm();
AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm);
vdsGroup = createVdsGroup();
mockStorageDomainDaoGetForStoragePool();
mockVmTemplateDaoReturnVmTemplate();
mockDiskImageDaoGetSnapshotById();
mockVerifyAddVM(cmd);
mockConfig();
mockMaxPciSlots();
mockStorageDomainDaoGetAllStoragesForPool(20);
mockUninterestingMethods(cmd);
mockDisplayTypes(vm.getOs());
mockGraphicsDevices(vm.getId());
doReturn(true).when(cmd).checkCpuSockets();
doReturn(vdsGroup).when(cmd).getVdsGroup();
doReturn(createStoragePool()).when(cmd).getStoragePool();
cmd.getParameters().setVirtioScsiEnabled(true);
when(osRepository.isSoundDeviceEnabled(any(Integer.class), any(Version.class))).thenReturn(true);
when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.x86_64);
when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn(
new ArrayList<>(Collections.singletonList("VirtIO")));
mockGetAllSnapshots(cmd);
CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd,
EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI);
}
@Test
public void isVirtioScsiEnabledDefaultedToTrue() {
AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(0);
doReturn(createVdsGroup()).when(cmd).getVdsGroup();
when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn(
new ArrayList<>(Collections.singletonList("VirtIO_SCSI")));
assertTrue("isVirtioScsiEnabled hasn't been defaulted to true on cluster >= 3.3.", cmd.isVirtioScsiEnabled());
}
@Test
public void validateSpaceAndThreshold() {
AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0);
doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds();
doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForNewDisks(anyList());
doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
assertTrue(command.validateSpaceRequirements());
verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForNewDisks(anyList());
verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList());
}
@Test
public void validateSpaceNotEnough() throws Exception {
AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0);
doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds();
doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)).
when(storageDomainValidator).hasSpaceForNewDisks(anyList());
doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
assertFalse(command.validateSpaceRequirements());
verify(storageDomainValidator).hasSpaceForNewDisks(anyList());
verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList());
}
@Test
public void validateSpaceNotWithinThreshold() throws Exception {
AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0);
doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)).
when(storageDomainValidator).isDomainWithinThresholds();
doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
assertFalse(command.validateSpaceRequirements());
}
@Test
public void testUnsupportedCpus() {
// prepare a command to pass canDo action
VM vm = createVm();
vm.setVmOs(OsRepository.DEFAULT_X86_OS);
vdsGroup = createVdsGroup();
AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm);
mockStorageDomainDaoGetForStoragePool();
mockVmTemplateDaoReturnVmTemplate();
mockDiskImageDaoGetSnapshotById();
mockVerifyAddVM(cmd);
mockConfig();
mockMaxPciSlots();
mockStorageDomainDaoGetAllStoragesForPool(20);
mockDisplayTypes(vm.getOs());
mockUninterestingMethods(cmd);
mockGetAllSnapshots(cmd);
when(osRepository.getArchitectureFromOS(0)).thenReturn(ArchitectureType.x86_64);
doReturn(createStoragePool()).when(cmd).getStoragePool();
// prepare the mock values
Map<Pair<Integer, Version>, Set<String>> unsupported = new HashMap<>();
Set<String> value = new HashSet<>();
value.add(CPU_ID);
unsupported.put(new Pair<>(vm.getVmOsId(), vdsGroup.getCompatibilityVersion()), value);
when(osRepository.isCpuSupported(vm.getVmOsId(), vdsGroup.getCompatibilityVersion(), CPU_ID)).thenReturn(false);
when(osRepository.getUnsupportedCpus()).thenReturn(unsupported);
CanDoActionTestUtils.runAndAssertCanDoActionFailure(
cmd,
EngineMessage.CPU_TYPE_UNSUPPORTED_FOR_THE_GUEST_OS);
}
private void mockDisplayTypes(int osId) {
Map<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> displayTypeMap = new HashMap<>();
displayTypeMap.put(osId, new HashMap<Version, List<Pair<GraphicsType, DisplayType>>>());
displayTypeMap.get(osId).put(null, Collections.singletonList(new Pair<>(GraphicsType.SPICE, DisplayType.qxl)));
when(osRepository.getGraphicsAndDisplays()).thenReturn(displayTypeMap);
}
protected void mockNonInterestingMethodsForCloneVmFromSnapshot(AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd) {
mockUninterestingMethods(cmd);
doReturn(true).when(cmd).checkCpuSockets();
doReturn(null).when(cmd).getVmFromConfiguration();
}
private void mockMaxPciSlots() {
SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);
doReturn(MAX_PCI_SLOTS).when(osRepository).getMaxPciDevices(anyInt(), any(Version.class));
}
protected AddVmFromTemplateCommand<AddVmParameters> createVmFromTemplateCommand(VM vm) {
AddVmParameters param = new AddVmParameters();
param.setVm(vm);
AddVmFromTemplateCommand<AddVmParameters> concrete =
new AddVmFromTemplateCommand<AddVmParameters>(param) {
@Override
protected void initUser() {
// Stub for testing
}
@Override
protected void initTemplateDisks() {
// Stub for testing
}
@Override
protected void initStoragePoolId() {
// Stub for testing
}
@Override
public VmTemplate getVmTemplate() {
return createVmTemplate();
}
};
AddVmFromTemplateCommand<AddVmParameters> result = spy(concrete);
doReturn(true).when(result).checkNumberOfMonitors();
doReturn(createVmTemplate()).when(result).getVmTemplate();
doReturn(true).when(result).validateCustomProperties(any(VmStatic.class), anyList());
mockDaos(result);
mockBackend(result);
initCommandMethods(result);
result.postConstruct();
return result;
}
private AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> createVmFromSnapshotCommand(VM vm,
Guid sourceSnapshotId) {
AddVmFromSnapshotParameters param = new AddVmFromSnapshotParameters();
param.setVm(vm);
param.setSourceSnapshotId(sourceSnapshotId);
param.setStorageDomainId(Guid.newGuid());
AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd =
new AddVmFromSnapshotCommand<AddVmFromSnapshotParameters>(param) {
@Override
protected void initUser() {
// Stub for testing
}
@Override
protected void initTemplateDisks() {
// Stub for testing
}
@Override
protected void initStoragePoolId() {
// Stub for testing
}
@Override
public VmTemplate getVmTemplate() {
return createVmTemplate();
}
};
cmd = spy(cmd);
doReturn(vm).when(cmd).getVm();
mockDaos(cmd);
doReturn(snapshotDao).when(cmd).getSnapshotDao();
mockBackend(cmd);
return cmd;
}
protected AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> setupCanAddVmFromSnapshotTests
(final int domainSizeGB, Guid sourceSnapshotId) {
VM vm = initializeMock(domainSizeGB);
initializeVmDaoMock(vm);
AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = createVmFromSnapshotCommand(vm, sourceSnapshotId);
initCommandMethods(cmd);
return cmd;
}
private void initializeVmDaoMock(VM vm) {
when(vmDao.get(any(Guid.class))).thenReturn(vm);
}
private AddVmCommand<AddVmParameters> setupCanAddVmTests(final int domainSizeGB) {
VM vm = initializeMock(domainSizeGB);
AddVmCommand<AddVmParameters> cmd = createCommand(vm);
initCommandMethods(cmd);
doReturn(createVmTemplate()).when(cmd).getVmTemplate();
doReturn(createStoragePool()).when(cmd).getStoragePool();
return cmd;
}
private static <T extends AddVmParameters> void initCommandMethods(AddVmCommand<T> cmd) {
doReturn(Guid.newGuid()).when(cmd).getStoragePoolId();
doReturn(true).when(cmd).canAddVm(anyListOf(String.class), anyString(), any(Guid.class), anyInt());
doReturn(STORAGE_POOL_ID).when(cmd).getStoragePoolId();
}
private VM initializeMock(final int domainSizeGB) {
mockVmTemplateDaoReturnVmTemplate();
mockDiskImageDaoGetSnapshotById();
mockStorageDomainDaoGetForStoragePool(domainSizeGB);
mockStorageDomainDaoGet(domainSizeGB);
mockConfig();
return createVm();
}
private void mockBackend(AddVmCommand<?> cmd) {
when(backend.getResourceManager()).thenReturn(vdsBrokerFrontend);
doReturn(backend).when(cmd).getBackend();
}
private void mockDaos(AddVmCommand<?> cmd) {
doReturn(vmDao).when(cmd).getVmDao();
doReturn(sdDao).when(cmd).getStorageDomainDao();
doReturn(vmTemplateDao).when(cmd).getVmTemplateDao();
doReturn(vdsGroupDao).when(cmd).getVdsGroupDao();
doReturn(deviceDao).when(cmd).getVmDeviceDao();
}
private void mockStorageDomainDaoGetForStoragePool(int domainSpaceGB) {
when(sdDao.getForStoragePool(any(Guid.class), any(Guid.class))).thenReturn(createStorageDomain(domainSpaceGB));
}
private void mockStorageDomainDaoGet(final int domainSpaceGB) {
doAnswer(new Answer<StorageDomain>() {
@Override
public StorageDomain answer(InvocationOnMock invocation) throws Throwable {
StorageDomain result = createStorageDomain(domainSpaceGB);
result.setId((Guid) invocation.getArguments()[0]);
return result;
}
}).when(sdDao).get(any(Guid.class));
}
private void mockStorageDomainDaoGetAllStoragesForPool(int domainSpaceGB) {
when(sdDao.getAllForStoragePool(any(Guid.class))).thenReturn(Collections.singletonList(createStorageDomain(domainSpaceGB)));
}
private void mockStorageDomainDaoGetForStoragePool() {
mockStorageDomainDaoGetForStoragePool(AVAILABLE_SPACE_GB);
}
private void mockVmTemplateDaoReturnVmTemplate() {
when(vmTemplateDao.get(any(Guid.class))).thenReturn(createVmTemplate());
}
private void mockVdsGroupDaoReturnVdsGroup() {
when(vdsGroupDao.get(any(Guid.class))).thenReturn(createVdsGroup());
}
private VmTemplate createVmTemplate() {
if (vmTemplate == null) {
vmTemplate = new VmTemplate();
vmTemplate.setStoragePoolId(STORAGE_POOL_ID);
DiskImage image = createDiskImageTemplate();
vmTemplate.getDiskTemplateMap().put(image.getImageId(), image);
HashMap<Guid, DiskImage> diskImageMap = new HashMap<>();
DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB);
diskImageMap.put(diskImage.getId(), diskImage);
vmTemplate.setDiskImageMap(diskImageMap);
}
return vmTemplate;
}
private VDSGroup createVdsGroup() {
if (vdsGroup == null) {
vdsGroup = new VDSGroup();
vdsGroup.setVdsGroupId(Guid.newGuid());
vdsGroup.setCompatibilityVersion(Version.v3_3);
vdsGroup.setCpuName("Intel Conroe Family");
vdsGroup.setArchitecture(ArchitectureType.x86_64);
}
return vdsGroup;
}
private StoragePool createStoragePool() {
if (storagePool == null) {
storagePool = new StoragePool();
storagePool.setId(STORAGE_POOL_ID);
storagePool.setStatus(StoragePoolStatus.Up);
}
return storagePool;
}
private static DiskImage createDiskImageTemplate() {
DiskImage i = new DiskImage();
i.setSizeInGigabytes(USED_SPACE_GB + AVAILABLE_SPACE_GB);
i.setActualSizeInBytes(REQUIRED_DISK_SIZE_GB * 1024L * 1024L * 1024L);
i.setImageId(Guid.newGuid());
i.setStorageIds(new ArrayList<>(Collections.singletonList(STORAGE_DOMAIN_ID_1)));
return i;
}
private void mockDiskImageDaoGetSnapshotById() {
when(diskImageDao.getSnapshotById(any(Guid.class))).thenReturn(createDiskImage(REQUIRED_DISK_SIZE_GB));
}
private static DiskImage createDiskImage(int size) {
DiskImage diskImage = new DiskImage();
diskImage.setSizeInGigabytes(size);
diskImage.setActualSize(size);
diskImage.setId(Guid.newGuid());
diskImage.setImageId(Guid.newGuid());
diskImage.setStorageIds(new ArrayList<>(Collections.singletonList(STORAGE_DOMAIN_ID_1)));
return diskImage;
}
protected StorageDomain createStorageDomain(int availableSpace) {
StorageDomain sd = new StorageDomain();
sd.setStorageDomainType(StorageDomainType.Master);
sd.setStatus(StorageDomainStatus.Active);
sd.setAvailableDiskSize(availableSpace);
sd.setUsedDiskSize(USED_SPACE_GB);
sd.setId(STORAGE_DOMAIN_ID_1);
return sd;
}
private static void mockVerifyAddVM(AddVmCommand<?> cmd) {
doReturn(true).when(cmd).verifyAddVM(anyListOf(String.class), anyInt());
}
private void mockConfig() {
mcr.mockConfigValue(ConfigValues.PredefinedVMProperties, Version.v3_0, "");
mcr.mockConfigValue(ConfigValues.UserDefinedVMProperties, Version.v3_0, "");
mcr.mockConfigValue(ConfigValues.InitStorageSparseSizeInGB, 1);
mcr.mockConfigValue(ConfigValues.VirtIoScsiEnabled, Version.v3_3, true);
mcr.mockConfigValue(ConfigValues.ValidNumOfMonitors, Arrays.asList("1,2,4".split(",")));
mcr.mockConfigValue(ConfigValues.IsMigrationSupported, Version.v3_3, migrationMap);
mcr.mockConfigValue(ConfigValues.MaxIoThreadsPerVm, 127);
}
protected static VM createVm() {
VM vm = new VM();
VmDynamic dynamic = new VmDynamic();
VmStatic stat = new VmStatic();
stat.setVmtGuid(Guid.newGuid());
stat.setName("testVm");
stat.setPriority(1);
vm.setStaticData(stat);
vm.setDynamicData(dynamic);
vm.setSingleQxlPci(false);
return vm;
}
private AddVmCommand<AddVmParameters> createCommand(VM vm) {
AddVmParameters param = new AddVmParameters(vm);
AddVmCommand<AddVmParameters> cmd = new AddVmCommand<AddVmParameters>(param) {
@Override
protected void initUser() {
// Stub for testing
}
@Override
protected void initTemplateDisks() {
// Stub for testing
}
@Override
protected void initStoragePoolId() {
// stub for testing
}
@Override
public VmTemplate getVmTemplate() {
return createVmTemplate();
}
};
cmd = spy(cmd);
mockDaos(cmd);
mockBackend(cmd);
doReturn(new VDSGroup()).when(cmd).getVdsGroup();
generateStorageToDisksMap(cmd);
initDestSDs(cmd);
storageDomainValidator = mock(StorageDomainValidator.class);
doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds();
doReturn(storageDomainValidator).when(cmd).createStorageDomainValidator(any(StorageDomain.class));
return cmd;
}
protected void generateStorageToDisksMap(AddVmCommand<? extends AddVmParameters> command) {
command.storageToDisksMap = new HashMap<>();
command.storageToDisksMap.put(STORAGE_DOMAIN_ID_1, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_1));
command.storageToDisksMap.put(STORAGE_DOMAIN_ID_2, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_2));
}
private static List<DiskImage> generateDisksList(int size) {
List<DiskImage> disksList = new ArrayList<>();
for (int i = 0; i < size; ++i) {
DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB);
disksList.add(diskImage);
}
return disksList;
}
protected void initDestSDs(AddVmCommand<? extends AddVmParameters> command) {
StorageDomain sd1 = new StorageDomain();
StorageDomain sd2 = new StorageDomain();
sd1.setId(STORAGE_DOMAIN_ID_1);
sd2.setId(STORAGE_DOMAIN_ID_2);
command.destStorages.put(STORAGE_DOMAIN_ID_1, sd1);
command.destStorages.put(STORAGE_DOMAIN_ID_2, sd2);
}
protected List<DiskImage> createDiskSnapshot(Guid diskId, int numOfImages) {
List<DiskImage> disksList = new ArrayList<>();
for (int i = 0; i < numOfImages; ++i) {
DiskImage diskImage = new DiskImage();
diskImage.setActive(false);
diskImage.setId(diskId);
diskImage.setImageId(Guid.newGuid());
diskImage.setParentId(Guid.newGuid());
diskImage.setImageStatus(ImageStatus.OK);
disksList.add(diskImage);
}
return disksList;
}
private void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmParameters> command) {
doAnswer(new Answer<List<DiskImage>>() {
@Override
public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
DiskImage arg = (DiskImage) args[0];
return createDiskSnapshot(arg.getId(), 3);
}
}).when(command).getAllImageSnapshots(any(DiskImage.class));
}
private <T extends AddVmParameters> void mockUninterestingMethods(AddVmCommand<T> spy) {
doReturn(true).when(spy).isVmNameValidLength(any(VM.class));
doReturn(false).when(spy).isVmWithSameNameExists(anyString(), any(Guid.class));
doReturn(STORAGE_POOL_ID).when(spy).getStoragePoolId();
doReturn(createVmTemplate()).when(spy).getVmTemplate();
doReturn(createVdsGroup()).when(spy).getVdsGroup();
doReturn(true).when(spy).areParametersLegal(anyListOf(String.class));
doReturn(Collections.<VmNetworkInterface> emptyList()).when(spy).getVmInterfaces();
doReturn(Collections.<DiskImageBase> emptyList()).when(spy).getVmDisks();
doReturn(false).when(spy).isVirtioScsiControllerAttached(any(Guid.class));
doReturn(true).when(osRepository).isSoundDeviceEnabled(any(Integer.class), any(Version.class));
spy.setVmTemplateId(Guid.newGuid());
}
@Test
public void testBeanValidations() {
assertTrue(createCommand(initializeMock(1)).validateInputs());
}
@Test
public void testPatternBasedNameFails() {
AddVmCommand<AddVmParameters> cmd = createCommand(initializeMock(1));
cmd.getParameters().getVm().setName("aa-??bb");
assertFalse("Pattern-based name should not be supported for VM", cmd.validateInputs());
}
@Test
public void refuseBalloonOnPPC() {
AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest();
cmd.getParameters().setBalloonEnabled(true);
when(osRepository.isBalloonEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false);
CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH);
}
@Test
public void refuseSoundDeviceOnPPC() {
AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest();
cmd.getParameters().setSoundDeviceEnabled(true);
when(osRepository.isSoundDeviceEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false);
CanDoActionTestUtils.runAndAssertCanDoActionFailure
(cmd, EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH);
}
private AddVmCommand<AddVmParameters> setupCanAddPpcTest() {
final int domainSizeGB = 20;
AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB);
doReturn(true).when(cmd).validateSpaceRequirements();
doReturn(true).when(cmd).buildAndCheckDestStorageDomains();
cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64);
VDSGroup cluster = new VDSGroup();
cluster.setArchitecture(ArchitectureType.ppc64);
cluster.setCompatibilityVersion(Version.getLast());
doReturn(cluster).when(cmd).getVdsGroup();
return cmd;
}
@Test
public void testStoragePoolDoesntExist() {
final int domainSizeGB = 20;
AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB);
doReturn(null).when(cmd).getStoragePool();
CanDoActionTestUtils.runAndAssertCanDoActionFailure
(cmd, EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST);
}
}
|
package org.openforis.ceo;
import static org.openforis.ceo.JsonUtils.filterJsonArray;
import static org.openforis.ceo.JsonUtils.findInJsonArray;
import static org.openforis.ceo.JsonUtils.mapJsonArray;
import static org.openforis.ceo.JsonUtils.parseJson;
import static org.openforis.ceo.JsonUtils.readJsonFile;
import static org.openforis.ceo.JsonUtils.writeJsonFile;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.net.URLDecoder;
import java.util.Optional;
import java.util.UUID;
import spark.Request;
import spark.Response;
public class GeoDash {
public static synchronized String geodashId(Request req, Response res) {
String projectId = req.params(":id");
String projectTitle = req.queryParams("title");
String callback = req.queryParams("callback");
JsonArray projects = readJsonFile("proj.json").getAsJsonArray();
Optional<JsonObject> matchingProject = findInJsonArray(projects,
project -> project.get("projectID").getAsString().equals(projectId));
if (matchingProject.isPresent()) {
JsonObject project = matchingProject.get();
String dashboardId = project.get("dashboard").getAsString();
try {
String dashboardJson = readJsonFile("dash-" + dashboardId + ".json").toString();
if (callback != null) {
return callback + "(" + dashboardJson + ")";
} else {
return dashboardJson;
}
} catch (Exception e) {
// The dash-<dashboardId>.json file doesn't exist, so we need to create a blank one.
JsonObject newDashboard = new JsonObject();
newDashboard.addProperty("projectID", projectId);
newDashboard.addProperty("projectTitle", projectTitle);
newDashboard.add("widgets", new JsonArray());
newDashboard.addProperty("dashboardID", dashboardId);
writeJsonFile("dash-" + dashboardId + ".json", newDashboard);
if (callback != null) {
return callback + "(" + newDashboard.toString() + ")";
} else {
return newDashboard.toString();
}
}
} else {
String newDashboardId = UUID.randomUUID().toString();
JsonObject newProject = new JsonObject();
newProject.addProperty("projectID", projectId);
newProject.addProperty("dashboard", newDashboardId);
projects.add(newProject);
writeJsonFile("proj.json", projects);
JsonObject newDashboard = new JsonObject();
newDashboard.addProperty("projectID", projectId);
newDashboard.addProperty("projectTitle", projectTitle);
newDashboard.add("widgets", new JsonArray());
newDashboard.addProperty("dashboardID", newDashboardId);
writeJsonFile("dash-" + newDashboardId + ".json", newDashboard);
if (callback != null) {
return callback + "(" + newDashboard.toString() + ")";
} else {
return newDashboard.toString();
}
}
}
public static synchronized String updateDashBoardByID(Request req, Response res) {
/* Code will go here to update dashboard*/
return "";
}
public static synchronized String createDashBoardWidgetByID(Request req, Response res) {
String dashboardId = req.queryParams("dashID");
String widgetJson = req.queryParams("widgetJSON");
String callback = req.queryParams("callback");
JsonObject dashboard = readJsonFile("dash-" + dashboardId + ".json").getAsJsonObject();
JsonArray widgets = dashboard.getAsJsonArray("widgets");
try {
JsonObject newWidget = parseJson(URLDecoder.decode(widgetJson, "UTF-8")).getAsJsonObject();
widgets.add(newWidget);
} catch (Exception e) {
throw new RuntimeException(e);
}
dashboard.add("widgets", widgets);
writeJsonFile("dash-" + dashboardId + ".json", dashboard);
if (callback != null) {
return callback + "()";
} else {
return "";
}
}
public static synchronized String updateDashBoardWidgetByID(Request req, Response res) {
String dashboardId = req.queryParams("dashID");
String widgetId = req.params(":id");
String widgetJson = req.queryParams("widgetJSON");
String callback = req.queryParams("callback");
JsonObject dashboard = readJsonFile("dash-" + dashboardId + ".json").getAsJsonObject();
JsonArray widgets = dashboard.getAsJsonArray("widgets");
JsonArray updatedWidgets = mapJsonArray(widgets, widget -> {
if (widget.get("id").getAsString().equals(widgetId)) {
try {
return parseJson(URLDecoder.decode(widgetJson, "UTF-8")).getAsJsonObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return widget;
}
});
dashboard.add("widgets", updatedWidgets);
writeJsonFile("dash-" + dashboardId + ".json", dashboard);
if (callback != null) {
return callback + "()";
} else {
return "";
}
}
public static synchronized String deleteDashBoardWidgetByID(Request req, Response res) {
String dashboardId = req.queryParams("dashID");
String widgetId = req.params(":id");
String callback = req.queryParams("callback");
JsonObject dashboard = readJsonFile("dash-" + dashboardId + ".json").getAsJsonObject();
JsonArray widgets = dashboard.getAsJsonArray("widgets");
JsonArray updatedWidgets = filterJsonArray(widgets, widget -> !widget.get("id").getAsString().equals(widgetId));
dashboard.add("widgets", updatedWidgets);
writeJsonFile("dash-" + dashboardId + ".json", dashboard);
if (callback != null) {
return callback + "()";
} else {
return "";
}
}
}
|
package org.jboss.hal.testsuite.test.configuration.undertow;
import org.apache.commons.lang.RandomStringUtils;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.testsuite.category.Shared;
import org.jboss.hal.testsuite.dmr.AddressTemplate;
import org.jboss.hal.testsuite.dmr.Dispatcher;
import org.jboss.hal.testsuite.dmr.Operation;
import org.jboss.hal.testsuite.dmr.ResourceAddress;
import org.jboss.hal.testsuite.fragment.ConfigFragment;
import org.jboss.hal.testsuite.fragment.formeditor.Editor;
import org.jboss.hal.testsuite.fragment.shared.modal.WizardWindow;
import org.jboss.hal.testsuite.page.config.UndertowHTTPPage;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.IOException;
@RunWith(Arquillian.class)
@Category(Shared.class)
public class HostTestCase extends UndertowTestCaseAbstract {
@Page
UndertowHTTPPage page;
private final String ALIAS = "alias_i";
private final String DEFAULT_RESPONSE_CODE = "default-response-code";
private final String DEFAULT_WEB_MODULE = "default-web-module";
private final String DISABLE_CONSOLE_REDIRECT = "disable-console-redirect";
private final String ALIAS_ATTR = "alias_i";
private final String DEFAULT_RESPONSE_CODE_ATTR = "default-response-code";
private final String DEFAULT_WEB_MODULE_ATTR = "default-web-module";
private final String DISABLE_CONSOLE_REDIRECT_ATTR = "disable-console-redirect";
//values
private final String[] ALIAS_VALUES = new String[]{"localhost", "test", "example"};
private final String DEFAULT_RESPONSE_CODE_VALUE = "500";
private static String httpServer;
private AddressTemplate hostTemplate = undertowAddressTemplate.append("/host=*");
private String httpServerHost;
private ResourceAddress address;
@BeforeClass
public static void setUp() {
httpServer = operations.createHTTPServer();
}
@Before
public void before() {
httpServerHost = createHTTPServerHostHost(dispatcher);
address = hostTemplate.resolve(context, httpServer, httpServerHost);
page.navigate();
page.viewHTTPServer(httpServer).switchToHosts();
}
@After
public void after() {
removeHTTPServerHost(httpServerHost);
}
@AfterClass
public static void tearDown() {
operations.removeHTTPServer(httpServer);
}
@Test
public void editAliases() throws IOException, InterruptedException {
editTextAreaAndVerify(address, ALIAS, ALIAS_ATTR, ALIAS_VALUES);
}
@Test
public void editDefaultResponseCode() throws IOException, InterruptedException {
editTextAndVerify(address, DEFAULT_RESPONSE_CODE, DEFAULT_RESPONSE_CODE_ATTR, DEFAULT_RESPONSE_CODE_VALUE);
}
@Test
public void editDefaultWebModule() throws IOException, InterruptedException {
editTextAndVerify(address, DEFAULT_WEB_MODULE, DEFAULT_WEB_MODULE_ATTR);
}
@Test
public void setDisableConsoleRedirectToTrue() throws IOException, InterruptedException {
editCheckboxAndVerify(address, DISABLE_CONSOLE_REDIRECT, DISABLE_CONSOLE_REDIRECT_ATTR, true);
}
@Test
public void setDisableConsoleRedirectToFalse() throws IOException, InterruptedException {
editCheckboxAndVerify(address, DISABLE_CONSOLE_REDIRECT, DISABLE_CONSOLE_REDIRECT_ATTR, false);
}
@Test
public void addHTTPServerHostInGUI() {
String name = RandomStringUtils.randomAlphanumeric(6);
String webModule = RandomStringUtils.randomAlphanumeric(6);
ConfigFragment config = page.getConfigFragment();
WizardWindow wizard = config.getResourceManager().addResource();
Editor editor = wizard.getEditor();
editor.text("name", name);
editor.text(ALIAS, String.join("\n", ALIAS_VALUES));
editor.text(DEFAULT_RESPONSE_CODE, DEFAULT_RESPONSE_CODE_VALUE);
editor.text(DEFAULT_WEB_MODULE, webModule);
editor.checkbox(DISABLE_CONSOLE_REDIRECT, true);
boolean result = wizard.finish();
Assert.assertTrue("Window should be closed", result);
Assert.assertTrue("HTTP server host should be present in table", config.resourceIsPresent(name));
ResourceAddress address = hostTemplate.resolve(context, httpServer, name);
verifier.verifyResource(address, true);
verifier.verifyAttribute(address, ALIAS_ATTR, ALIAS_VALUES);
verifier.verifyAttribute(address, DEFAULT_RESPONSE_CODE_ATTR, DEFAULT_RESPONSE_CODE_VALUE);
verifier.verifyAttribute(address, DEFAULT_WEB_MODULE_ATTR, webModule);
verifier.verifyAttribute(address, DISABLE_CONSOLE_REDIRECT, true);
}
@Test
public void removeHTTPServerHostInGUI(String name) {
ConfigFragment config = page.getConfigFragment();
config.getResourceManager()
.removeResource(name)
.confirm();
Assert.assertFalse("HTTP server host should not be present in table", config.resourceIsPresent(name));
ResourceAddress address = hostTemplate.resolve(context, httpServer, name);
verifier.verifyResource(address, false); //HTTP server host should not be present on the server
}
private String createHTTPServerHostHost(Dispatcher dispatcher) {
String name = RandomStringUtils.randomAlphanumeric(6);
ResourceAddress address = hostTemplate.resolve(context, httpServer, name);
dispatcher.execute(new Operation.Builder("add", address).build());
return name;
}
private boolean removeHTTPServerHost(String ajpListener) {
ResourceAddress address = hostTemplate.resolve(context, httpServer, ajpListener);
return dispatcher.execute(new Operation.Builder("remove", address).build()).isSuccessful();
}
}
|
package org.takes.http;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import lombok.EqualsAndHashCode;
/**
* Front remote control.
*
* <p>The class is immutable and thread-safe.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.23
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
@SuppressWarnings("PMD.DoNotUseThreads")
@EqualsAndHashCode(of = "app")
public final class MainRemote {
/**
* Application with {@code main()} method.
*/
private final transient Class<?> app;
/**
* Additional arguments to be passed to the main class.
*/
private final transient String[] args;
/**
* Ctor.
* @param type Class with main method
*/
public MainRemote(final Class<?> type) {
this(type, new String[0]);
}
/**
* Ctor.
* @param type Class with main method
* @param args Additional arguments to be passed to the main method
*/
public MainRemote(final Class<?> type, final String... args) {
this.app = type;
this.args = Arrays.copyOf(args, args.length);
}
/**
* Execute this script against a running front.
* @param script Script to run
* @throws Exception If fails
*/
public void exec(final MainRemote.Script script) throws Exception {
final File file = File.createTempFile("takes-", ".txt");
file.delete();
final Method method = this.app.getDeclaredMethod(
"main", String[].class
);
final String[] args = new String[1 + this.args.length];
args[0] = String.format("--port=%s", file.getAbsoluteFile());
for (int idx = 0; idx < this.args.length; ++idx) {
args[idx + 1] = this.args[idx];
}
final Thread thread = new Thread(
new Runnable() {
@Override
public void run() {
try {
method.invoke(null, (Object) args);
} catch (final InvocationTargetException ex) {
throw new IllegalStateException(ex);
} catch (final IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
}
}
);
thread.start();
try {
script.exec(
URI.create(
String.format(
"http://localhost:%d",
MainRemote.port(file)
)
)
);
} finally {
file.delete();
thread.interrupt();
}
}
/**
* Read port number from file.
* @param file The file
* @return Port number
* @throws Exception If fails
*/
private static int port(final File file) throws Exception {
while (!file.exists()) {
TimeUnit.MILLISECONDS.sleep(1L);
}
final int port;
final InputStream input = new FileInputStream(file);
try {
// @checkstyle MagicNumber (1 line)
final byte[] buf = new byte[10];
while (true) {
if (input.read(buf) > 0) {
break;
}
}
port = Integer.parseInt(new String(buf).trim());
} finally {
input.close();
}
return port;
}
/**
* Script to execute.
*/
public interface Script {
/**
* Execute it against this URI.
* @param home URI of the running front
* @throws IOException If fails
*/
void exec(URI home) throws IOException;
}
}
|
package io.scalecube.services.benchmarks;
import java.io.File;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class ServicesBenchmarksSettings {
private static final int N_THREADS = Runtime.getRuntime().availableProcessors();
private static final Duration EXECUTION_TASK_TIME = Duration.ofSeconds(60);
private static final Duration REPORTER_PERIOD = Duration.ofSeconds(10);
private static final int RESPONSE_COUNT = 100;
private final int nThreads;
private final Duration executionTaskTime;
private final Duration reporterPeriod;
private final File csvReporterDirectory;
private final int responseCount;
private final String taskName;
private ServicesBenchmarksSettings(Builder builder) {
this.nThreads = builder.nThreads;
this.executionTaskTime = builder.executionTaskTime;
this.reporterPeriod = builder.reporterPeriod;
this.responseCount = builder.responseCount;
this.taskName = builder.taskName;
String time = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));
this.csvReporterDirectory = Paths.get(".", this.taskName, time).toFile();
// noinspection ResultOfMethodCallIgnored
this.csvReporterDirectory.mkdirs();
}
public int nThreads() {
return nThreads;
}
public Duration executionTaskTime() {
return executionTaskTime;
}
public Duration reporterPeriod() {
return reporterPeriod;
}
public File csvReporterDirectory() {
return csvReporterDirectory;
}
public int responseCount() {
return responseCount;
}
public String taskName() {
return taskName;
}
public static Builder builder() {
return new Builder();
}
public static Builder from(String[] args) {
Builder builder = builder();
if (args != null) {
for (String pair : args) {
String[] keyValue = pair.split("=", 2);
String key = keyValue[0];
String value = keyValue[1];
switch (key) {
case "nThreads":
builder.nThreads(Integer.parseInt(value));
break;
case "executionTaskTimeInSec":
builder.executionTaskTime(Duration.ofSeconds(Long.parseLong(value)));
break;
case "reporterPeriodInSec":
builder.reporterPeriod(Duration.ofSeconds(Long.parseLong(value)));
break;
case "responseCount":
builder.responseCount(Integer.parseInt(value));
break;
case "taskName":
builder.taskName(value);
break;
default:
throw new IllegalArgumentException("unknown command: " + pair);
}
}
}
return builder;
}
@Override
public String toString() {
return "ServicesBenchmarksSettings{" +
"nThreads=" + nThreads +
", executionTaskTime=" + executionTaskTime +
", reporterPeriod=" + reporterPeriod +
", csvReporterDirectory=" + csvReporterDirectory +
", responseCount=" + responseCount +
", taskName='" + taskName + '\'' +
'}';
}
public static class Builder {
private Integer nThreads = N_THREADS;
private Duration executionTaskTime = EXECUTION_TASK_TIME;
private Duration reporterPeriod = REPORTER_PERIOD;
private Integer responseCount = RESPONSE_COUNT;
private String taskName;
private Builder() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
this.taskName = stackTrace[stackTrace.length - 1].getClassName();
}
public Builder nThreads(Integer nThreads) {
this.nThreads = nThreads;
return this;
}
public Builder executionTaskTime(Duration executionTaskTime) {
this.executionTaskTime = executionTaskTime;
return this;
}
public Builder reporterPeriod(Duration reporterPeriod) {
this.reporterPeriod = reporterPeriod;
return this;
}
public Builder responseCount(Integer responseCount) {
this.responseCount = responseCount;
return this;
}
public Builder taskName(String taskName) {
this.taskName = taskName;
return this;
}
public ServicesBenchmarksSettings build() {
return new ServicesBenchmarksSettings(this);
}
}
}
|
package rx.broadcast;
import rx.Observable;
import rx.Subscriber;
import rx.broadcast.time.Clock;
import rx.broadcast.time.LamportClock;
import rx.schedulers.Schedulers;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public final class UdpBroadcast implements Broadcast {
private static final int MAX_UDP_PACKET_SIZE = 65535;
private static final int BYTES_LONG = 8;
private final Clock clock = new LamportClock();
private final DatagramSocket socket;
private final Observable<Object> values;
private final ConcurrentHashMap<Class, Observable> streams;
private final KryoSerializer serializer;
private final InetAddress destinationAddress;
private final int destinationPort;
private final BroadcastOrder<Object> order;
@SuppressWarnings("RedundantTypeArguments")
public UdpBroadcast(
final DatagramSocket socket,
final InetAddress destinationAddress,
final int destinationPort,
final BroadcastOrder<Object> order
) {
this.socket = socket;
this.order = order;
this.values = Observable.<Object>create(this::receive).subscribeOn(Schedulers.io()).share();
this.serializer = new KryoSerializer();
this.streams = new ConcurrentHashMap<>();
this.destinationAddress = destinationAddress;
this.destinationPort = destinationPort;
}
@Override
public Observable<Void> send(final Object value) {
return Observable.defer(() ->
clock.<Observable<Void>>tick(time -> {
try {
final byte[] data = serializer.serialize(new Timestamped<>(time, value));
final DatagramPacket packet = new DatagramPacket(
data, data.length, destinationAddress, destinationPort);
socket.send(packet);
return Observable.empty();
} catch (final Throwable e) {
return Observable.error(e);
}
}));
}
@Override
@SuppressWarnings("unchecked")
public <T> Observable<T> valuesOfType(final Class<T> clazz) {
return (Observable<T>) streams.computeIfAbsent(clazz, k -> values.filter(k::isInstance).cast(k).share());
}
@SuppressWarnings("unchecked")
private void receive(final Subscriber<Object> subscriber) {
final Consumer<Object> consumer = subscriber::onNext;
while (true) {
if (subscriber.isUnsubscribed()) {
break;
}
final byte[] buffer = new byte[MAX_UDP_PACKET_SIZE];
final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
} catch (final IOException e) {
subscriber.onError(e);
break;
}
final InetAddress address = packet.getAddress();
final int port = packet.getPort();
final long sender = ByteBuffer.allocate(BYTES_LONG).put(address.getAddress()).putInt(port).getLong(0);
final byte[] data = Arrays.copyOf(buffer, packet.getLength());
order.receive(sender, consumer, (Timestamped<Object>) serializer.deserialize(data));
}
}
}
|
package org.intermine.bio.dataconversion;
import java.io.Reader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.FormattedTextParser;
import org.intermine.xml.full.Item;
/**
*
* @author Julie
*/
public class ClinvarConverter extends BioFileConverter
{
private static final Logger LOG = Logger.getLogger(ClinvarConverter.class);
private static final String DATASET_TITLE = "ClinVar data set";
private static final String DATA_SOURCE_NAME = "ClinVar";
private static final String ASSEMBLY = "GRCh38";
private static final String TAXON_ID = "9606";
protected Map<String, String> genes = new HashMap<String, String>();
protected Map<String, String> diseases = new HashMap<String, String>();
protected Set<String> alleles = new HashSet<String>();
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public ClinvarConverter(ItemWriter writer, Model model) {
super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
*
*
* {@inheritDoc}
*/
public void process(Reader reader) throws Exception {
Iterator lineIter = FormattedTextParser.parseTabDelimitedReader(reader);
while (lineIter.hasNext()) {
String[] line = (String[]) lineIter.next();
if (line.length < 26) {
LOG.error("Allele not processed, only had " + line.length + " columns");
continue;
}
String alleleId = line [0];
if (alleleId.startsWith("
// skip header
continue;
}
String type = line[1];
String geneId = line[3];
String clinicalSignificance = line[6];
// String dbSNPXref = line[6];
// String ncbiXref = line[7];
// String clinVarXref = line[8];
String diseaseString = line[10]; // parse for OMIM
String assemblyString = line[16];
// only load GRCh38
if (!ASSEMBLY.equals(assemblyString)) {
continue;
}
if (alleles.contains(alleleId)) {
LOG.error("Duplicate alleles found for " + alleleId);
continue;
}
alleles.add(alleleId);
String referenceAllele = line[21];
String alternateAllele = line[22];
String geneRefId = getGene(geneId);
Item item = createItem("Allele");
item.setAttribute("primaryIdentifier", alleleId);
item.setAttribute("type", type);
item.setAttribute("clinicalSignificance", clinicalSignificance);
item.setAttribute("reference", referenceAllele);
item.setAttribute("alternate", alternateAllele);
item.setReference("organism", getOrganism(TAXON_ID));
item.setReference("gene", geneRefId);
String diseaseRefId = getDisease(diseaseString);
if (diseaseRefId != null) {
item.addToCollection("diseases", diseaseRefId);
}
store(item);
// if (!"-".equals(dbSNPXref)) {
// createCrossReference(item.getIdentifier(), dbSNPXref, "dbSNP", true);
// if (!"-".equals(ncbiXref)) {
// createCrossReference(item.getIdentifier(), ncbiXref, "NCBI", true);
// if (!"-".equals(clinVarXref)) {
// createCrossReference(item.getIdentifier(), clinVarXref, "ClinVar", true);
}
}
private String getGene(String identifier) throws ObjectStoreException {
String refId = genes.get(identifier);
if (refId != null) {
// we've already seen this gene
return refId;
}
Item item = createItem("Gene");
item.setAttribute("primaryIdentifier", identifier);
genes.put(identifier, item.getIdentifier());
store(item);
return item.getIdentifier();
}
// MedGen:C3150901,OMIM:613647,ORPHA:306511
private String getDisease(String diseaseString) throws ObjectStoreException {
String[] identifiers = diseaseString.split(",");
for (String identifier : identifiers) {
if (identifier.startsWith("OMIM")) {
String diseaseRefId = diseases.get(identifier);
if (diseaseRefId != null) {
return diseaseRefId;
}
// had issues with the data file. "OMIM:^@" was a value.
String[] bits = identifier.split(":");
if (bits.length != 2 || !StringUtils.isNumeric(bits[1])) {
return null;
}
Item item = createItem("Disease");
item.setAttribute("identifier", identifier);
diseases.put(identifier, item.getIdentifier());
store(item);
return item.getIdentifier();
}
}
return null;
}
}
|
package seedu.doist.ui;
import static javafx.scene.input.KeyCombination.CONTROL_DOWN;
import java.util.logging.Logger;
import org.fxmisc.richtext.InlineCssTextArea;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.SplitPane;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.doist.commons.core.LogsCenter;
import seedu.doist.commons.events.ui.NewResultAvailableEvent;
import seedu.doist.commons.util.FxViewUtil;
import seedu.doist.commons.util.History;
import seedu.doist.logic.Logic;
import seedu.doist.logic.commands.CommandResult;
import seedu.doist.logic.commands.RedoCommand;
import seedu.doist.logic.commands.UndoCommand;
import seedu.doist.logic.commands.exceptions.CommandException;
public class CommandBox extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(CommandBox.class);
private static final String FXML = "CommandBox.fxml";
public static final String ERROR_STYLE_CLASS = "error";
private static final String COMMAND_WORD_STYLE = "-fx-fill: orange;";
private static final String PARAMETER_KEY_STYLE = "-fx-fill: green;";
private static final String NORMAL_STYLE = "-fx-fill: black;";
private final Logic logic;
private final History<String> commandHistory = new History<String>();
private final KeyCombination undoKeys = new KeyCodeCombination(KeyCode.Z, CONTROL_DOWN);
private final KeyCombination redoKeys = new KeyCodeCombination(KeyCode.Y, CONTROL_DOWN);
@FXML
private InlineCssTextArea commandTextField;
public CommandBox(AnchorPane commandBoxPlaceholder, Logic logic) {
super(FXML);
this.logic = logic;
addToPlaceholder(commandBoxPlaceholder);
commandTextField.textProperty().addListener((observable, oldValue, newValue)
-> highlightSyntax(observable, oldValue, newValue));
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
placeHolderPane.getChildren().add(commandTextField);
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
FxViewUtil.applyAnchorBoundaryParameters(commandTextField, 0.0, 0.0, 0.0, 0.0);
}
private void highlightSyntax(ObservableValue<?> value, String oldValue, String newValue) {
String content = newValue;
int i = 0;
while (i < content.length() && content.charAt(i) != ' ') {
commandTextField.setStyle(i, i + 1, COMMAND_WORD_STYLE);
i++;
}
String key = "";
while (i < content.length()) {
if (content.charAt(i) == '\\') {
StringBuilder keyBuilder = new StringBuilder();
while (i < content.length() && content.charAt(i) != ' ') {
commandTextField.setStyle(i, i + 1, PARAMETER_KEY_STYLE);
keyBuilder.append(content.charAt(i));
i++;
}
key = keyBuilder.toString();
}
if (i >= content.length()) {
break;
}
if (key.equals("\\by") || key.equals("\\from") || key.equals("\\to")) {
commandTextField.setStyle(i, i + 1, "-fx-fill: blue;");
} else if (key.equals("\\as")) {
commandTextField.setStyle(i, i + 1, "-fx-fill: #cd5c5c;");
} else {
commandTextField.setStyle(i, i + 1, NORMAL_STYLE);
}
i++;
}
}
@FXML
private void handleKeyPressed(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
event.consume();
handleEnterKey();
} else if (event.getCode() == KeyCode.UP) {
// up and down arrow key will move the cursor to the position 0
// use consume() method to marks this Event as consumed. This stops such further propagation.
event.consume();
handleUpKey();
} else if (event.getCode() == KeyCode.DOWN) {
event.consume();
handleDownKey();
} else { // use control+z and control+y to execute undo and re-do operation
try {
if (undoKeys.match(event)) {
event.consume();
logic.execute(UndoCommand.DEFAULT_COMMAND_WORD);
} else if (redoKeys.match(event)) {
event.consume();
logic.execute(RedoCommand.DEFAULT_COMMAND_WORD);
}
} catch (CommandException e) {
// handle command failure
setStyleToIndicateCommandFailure();
setCommandInput("");
logger.info("Invalid command: " + commandTextField.getText());
raise(new NewResultAvailableEvent(e.getMessage()));
}
}
}
//Handles Down key press
private void handleDownKey() {
String userCommandText = commandHistory.getNextState();
if (userCommandText == null) {
setCommandInput("");
} else {
setCommandInput(userCommandText);
}
}
//Handle Up key press
private void handleUpKey() {
String userCommandText = commandHistory.getPreviousState();
if (userCommandText != null) {
setCommandInput(userCommandText);
}
}
//Handle Enter key press
private void handleEnterKey() {
try {
String userCommandText = commandTextField.getText();
restoreCommandHistoryAndAppend(userCommandText);
CommandResult commandResult = logic.execute(userCommandText);
// process result of the command
setStyleToIndicateCommandSuccess();
setCommandInput("");
logger.info("Result: " + commandResult.feedbackToUser);
raise(new NewResultAvailableEvent(commandResult.feedbackToUser));
} catch (CommandException e) {
// handle command failure
setStyleToIndicateCommandFailure();
setCommandInput("");
logger.info("Invalid command: " + commandTextField.getText());
raise(new NewResultAvailableEvent(e.getMessage()));
}
}
//Restores the command history pointer
//Throws exception is 'add' fails
private void restoreCommandHistoryAndAppend(String userCommandText) {
commandHistory.restore();
if (!commandHistory.addToHistory(userCommandText)) {
throw new ArrayIndexOutOfBoundsException();
}
}
private void setCommandInput(String string) {
commandTextField.replaceText(string);
// move the cursor to the end of the input string
commandTextField.positionCaret(string.length());
}
/**
* Sets the command box style to indicate a successful command.
*/
private void setStyleToIndicateCommandSuccess() {
commandTextField.getStyleClass().remove(ERROR_STYLE_CLASS);
}
/**
* Sets the command box style to indicate a failed command.
*/
private void setStyleToIndicateCommandFailure() {
commandTextField.getStyleClass().add(ERROR_STYLE_CLASS);
}
}
|
package seedu.typed.ui;
import java.util.ArrayList;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.typed.commons.core.LogsCenter;
import seedu.typed.commons.events.ui.NewResultAvailableEvent;
import seedu.typed.commons.util.FxViewUtil;
import seedu.typed.logic.Logic;
import seedu.typed.logic.commands.CommandResult;
import seedu.typed.logic.commands.exceptions.CommandException;
import seedu.typed.storage.temp.Session;
public class CommandBox extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(CommandBox.class);
private static final String FXML = "CommandBox.fxml";
public static final String ERROR_STYLE_CLASS = "error";
private final Logic logic;
@FXML
private TextField commandTextField;
private Session session;
private ArrayList<String> commandHistory;
private int pointer;
public CommandBox(AnchorPane commandBoxPlaceholder, Logic logic, Session session) {
super(FXML);
this.logic = logic;
this.session = session;
this.commandHistory = this.session.getAllCommandsHistory();
this.pointer = 0;
addToPlaceholder(commandBoxPlaceholder);
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
placeHolderPane.getChildren().add(commandTextField);
commandTextField.requestFocus();
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
FxViewUtil.applyAnchorBoundaryParameters(commandTextField, 0.0, 0.0, 0.0, 0.0);
}
@FXML
private void handleCommandInputChanged() {
try {
String commandInput = commandTextField.getText();
CommandResult commandResult = logic.execute(commandInput);
// process result of the command
setStyleToIndicateCommandSuccess();
commandTextField.clear();
resetPointer();
logger.info("Result: " + commandResult.feedbackToUser);
raise(new NewResultAvailableEvent(commandResult.feedbackToUser));
} catch (CommandException e) {
// handle command failure
setStyleToIndicateCommandFailure();
logger.info("Invalid command: " + commandTextField.getText());
resetPointer();
raise(new NewResultAvailableEvent(e.getMessage()));
}
}
//@@author A0139392X
@FXML
void handleKeyPressed(KeyEvent event) {
String keyPressed = event.getCode().toString();
switch(keyPressed) {
case "UP":
handleUpKey();
break;
case "DOWN":
handleDownKey();
break;
default:
break;
}
}
//@@author
/**
* Sets the command box style to indicate a successful command.
*/
private void setStyleToIndicateCommandSuccess() {
commandTextField.getStyleClass().remove(ERROR_STYLE_CLASS);
}
/**
* Sets the command box style to indicate a failed command.
*/
private void setStyleToIndicateCommandFailure() {
commandTextField.getStyleClass().add(ERROR_STYLE_CLASS);
}
//@@author A0143853A
private void resetPointer() {
pointer = commandHistory.size();
}
private boolean canUpPointer() {
if (pointer == 0) {
return false;
}
if (pointer > 0) {
pointer
}
if (pointer < commandHistory.size()) {
return true;
} else {
return false;
}
}
private boolean canDownPointer() {
if (pointer < (commandHistory.size() - 1)) {
pointer++;
return true;
} else {
return false;
}
}
private void handleUpKey() {
if (canUpPointer()) {
String commandToShow = getCommandFromHistory();
commandTextField.setText(commandToShow);
setCaretToEnd();
} else {
setCaretAtOriginal();
}
}
private void handleDownKey() {
if (canDownPointer()) {
String commandToShow = getCommandFromHistory();
commandTextField.setText(commandToShow);
setCaretToEnd();
} else {
resetPointer();
commandTextField.clear();
}
}
private String getCommandFromHistory() {
return commandHistory.get(pointer);
}
private void setCaretToEnd() {
Platform.runLater(new Runnable() {
@Override
public void run() {
commandTextField.end();
}
});
}
private void setCaretAtOriginal() {
int originalPosition = commandTextField.getCaretPosition();
Platform.runLater(new Runnable() {
@Override
public void run() {
commandTextField.positionCaret(originalPosition);
}
});
}
//@@author
}
|
package com.dmdirc.config.binding;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Class to invoke a method or set a value on a field.
*/
public abstract class Invocation {
/**
* Invokes the specified element on the specified instance with the specified value.
*
* @param element Element to call, can be a {@link Method} or {@link Field}
* @param instance Instance to call the element on
* @param value Value to be passed to the element
*/
public void invoke(final AccessibleObject element, final Object instance, final Object value) {
if (element instanceof Field) {
invoke((Field) element, instance, value);
} else if (element instanceof Method) {
invoke((Method) element, instance, value);
} else {
throw new IllegalArgumentException("Can only invoke on a Field or Method.");
}
}
/**
* Sets a field on the specified instance to the specified value.
*
* @param field Field to set
* @param instance Instance to set the field on
* @param value Value to set the field to
*/
public abstract void invoke(final Field field, final Object instance, final Object value);
/**
* Sets a field on the specified instance to the specified value.
*
* @param method Method to call
* @param instance Instance to call the method on
* @param value Value to call the method with
*/
public abstract void invoke(final Method method, final Object instance, final Object value);
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
public final class MainPanel extends JPanel {
public static final Paint TEXTURE = makeTexturePaint();
private static int openFrameCount;
private MainPanel() {
super(new BorderLayout());
JPanel p1 = new JPanel();
p1.setOpaque(false);
JPanel p2 = new JPanel() {
@Override protected void paintComponent(Graphics g) {
// super.paintComponent(g);
g.setColor(new Color(0x64_64_32_32, true));
g.fillRect(0, 0, getWidth(), getHeight());
}
};
JPanel p3 = new JPanel() {
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(TEXTURE);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
JDesktopPane desktop = new JDesktopPane();
desktop.add(createFrame(p1));
desktop.add(createFrame(p2));
desktop.add(createFrame(p3));
URL url = getClass().getResource("tokeidai.jpg");
BufferedImage image = Optional.ofNullable(url)
.map(u -> {
try {
return ImageIO.read(u);
} catch (IOException ex) {
return makeMissingImage();
}
}).orElseGet(MainPanel::makeMissingImage);
desktop.setBorder(new CentredBackgroundBorder(image));
// [JDK-6655001] D3D/OGL: Window translucency doesn't work with accelerated pipelines - Java Bug System
// desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
add(desktop);
add(createMenuBar(), BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
private JMenuBar createMenuBar() {
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_D);
JMenuItem menuItem = menu.add("New Frame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_DOWN_MASK));
menuItem.setActionCommand("new");
menuItem.addActionListener(e -> createFrame(null));
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static JInternalFrame createFrame(JComponent c) {
String title = String.format("Frame #%s", ++openFrameCount);
JInternalFrame frame = new JInternalFrame(title, true, true, true, true);
if (c instanceof JPanel) {
JPanel p = (JPanel) c;
p.add(new JLabel("label"));
p.add(new JButton("button"));
frame.setContentPane(p);
}
frame.setSize(160, 100);
frame.setLocation(30 * openFrameCount, 30 * openFrameCount);
frame.setOpaque(false);
frame.setVisible(true);
// desktop.getDesktopManager().activateFrame(frame);
return frame;
}
private static TexturePaint makeTexturePaint() {
BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setPaint(new Color(0x64_64_78_64, true));
g2.fillRect(0, 0, 16, 16);
int cs = 4;
for (int i = 0; i * cs < 16; i++) {
for (int j = 0; j * cs < 16; j++) {
if ((i + j) % 2 == 0) {
g2.fillRect(i * cs, j * cs, cs, cs);
}
}
}
g2.dispose();
return new TexturePaint(img, new Rectangle(16, 16));
}
private static BufferedImage makeMissingImage() {
Icon missingIcon = UIManager.getIcon("OptionPane.errorIcon");
int w = missingIcon.getIconWidth();
int h = missingIcon.getIconHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
missingIcon.paintIcon(null, g2, 0, 0);
g2.dispose();
return bi;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class CentredBackgroundBorder implements Border {
private final BufferedImage image;
protected CentredBackgroundBorder(BufferedImage image) {
this.image = image;
}
@Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
int cx = (width - image.getWidth()) / 2;
int cy = (height - image.getHeight()) / 2;
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
g2.drawRenderedImage(image, AffineTransform.getTranslateInstance(cx, cy));
g2.dispose();
}
@Override public Insets getBorderInsets(Component c) {
return new Insets(0, 0, 0, 0);
}
@Override public boolean isBorderOpaque() {
return true;
}
}
|
package gov.nih.nci.cabig.caaers.domain;
import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name = "site_research_staffs")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = {@Parameter(name = "sequence", value = "seq_site_research_staffs_id") })
public class SiteResearchStaff extends AbstractMutableDomainObject{
private ResearchStaff researchStaff;
private Organization organization;
private List<StudyPersonnel> studyPersonnels;
private List<SiteResearchStaffRole> siteResearchStaffRoles;
private String emailAddress;
private String phoneNumber;
private String faxNumber;
private Address address;
private Boolean associateAllStudies;
///LOGIC
public SiteResearchStaffRole findSiteResearchStaffRole(SiteResearchStaffRole other){
for(SiteResearchStaffRole role : siteResearchStaffRoles){
if(StringUtils.equals(role.getRoleCode(), other.getRoleCode())) return role;
}
return null;
}
@OneToMany(mappedBy = "siteResearchStaff", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<SiteResearchStaffRole> getSiteResearchStaffRoles() {
return siteResearchStaffRoles;
}
public void setSiteResearchStaffRoles(
List<SiteResearchStaffRole> siteResearchStaffRoles) {
this.siteResearchStaffRoles = siteResearchStaffRoles;
}
/**
* Utility method to add SiteResearchRole
* @param siteResearchStaffRole
*/
public void addSiteResearchStaffRole(SiteResearchStaffRole siteResearchStaffRole){
if(getSiteResearchStaffRoles() == null){
siteResearchStaffRoles = new ArrayList<SiteResearchStaffRole>();
}
siteResearchStaffRole.setSiteResearchStaff(this);
getSiteResearchStaffRoles().add(siteResearchStaffRole);
}
@OneToMany(mappedBy = "siteResearchStaff", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyPersonnel> getStudyPersonnels() {
return studyPersonnels;
}
public void setStudyPersonnels(List<StudyPersonnel> studyPersonnels) {
this.studyPersonnels = studyPersonnels;
}
/**
* Utility method to add StudyPersonnel
* @param studyPersonnel
*/
public void addStudyPersonnel(StudyPersonnel studyPersonnel){
if(getStudyPersonnels() == null){
this.studyPersonnels = new ArrayList<StudyPersonnel>();
}
studyPersonnel.setSiteResearchStaff(this);
getStudyPersonnels().add(studyPersonnel);
}
@ManyToOne
@JoinColumn(name = "researchstaff_id")
public ResearchStaff getResearchStaff() {
return researchStaff;
}
public void setResearchStaff(ResearchStaff researchStaff) {
this.researchStaff = researchStaff;
}
@ManyToOne
@JoinColumn(name = "site_id")
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
@Column(name = "email_address")
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
@Column(name = "phone_number")
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Column(name = "fax_number")
public String getFaxNumber() {
return faxNumber;
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
@Embedded
public Address getAddress() {
if(address == null) address = new Address();
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Transient
public boolean isActive(){
//return (startDate != null && DateUtils.between(new Date(), startDate, endDate));
return true;
}
@Transient
public boolean isInActive(){
//return (startDate == null || !DateUtils.between(new Date(), startDate, endDate));
return false;
}
// /OBJECT METHODS
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((researchStaff == null) ? 0 : researchStaff.hashCode());
result = prime * result + ((organization == null) ? 0 : organization.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final SiteResearchStaff other = (SiteResearchStaff) obj;
if (researchStaff == null) {
if (other.researchStaff != null) return false;
} else if (!researchStaff.equals(other.researchStaff)) return false;
if (organization == null) {
if (other.organization != null) return false;
} else if (!organization.equals(other.organization)) return false;
return true;
}
@Column(name = "associate_all_studies")
public Boolean getAssociateAllStudies() {
return associateAllStudies;
}
public void setAssociateAllStudies(Boolean associateAllStudies) {
this.associateAllStudies = associateAllStudies;
}
}
|
package tigase.xmpp.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.server.Iq;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
import java.util.TimeZone;
/**
* Class responsible for queuing packets (usable in connections from mobile
* clients - power usage optimization) version 3
*
* @author andrzej
*/
public class MobileV3
extends XMPPProcessor
implements XMPPProcessorIfc, XMPPPacketFilterIfc {
// default values
private static final int DEF_MAX_QUEUE_SIZE_VAL = 50;
private static final String ID = "mobile_v3";
private static final Logger log = Logger.getLogger(MobileV3.class.getCanonicalName());
// keys
private static final String MAX_QUEUE_SIZE_KEY = "max-queue-size";
private static final String MOBILE_EL_NAME = "mobile";
private static final String XMLNS = "http://tigase.org/protocol/mobile
private static final String[][] ELEMENT_PATHS = {
{ Iq.ELEM_NAME, MOBILE_EL_NAME }
};
private static final String[] XMLNSS = { XMLNS };
private static final Element[] SUP_FEATURES = { new Element(MOBILE_EL_NAME,
new String[] { "xmlns" }, new String[] { XMLNS }) };
private static final String PRESENCE_QUEUE_KEY = ID + "-presence-queue";
private static final String PACKET_QUEUE_KEY = ID + "-packet-queue";
private static final String DELAY_ELEM_NAME = "delay";
private static final String DELAY_XMLNS = "urn:xmpp:delay";
private static final String MESSAGE_ELEM_NAME = "message";
private static final ThreadLocal<Queue> prependResultsThreadQueue = new ThreadLocal<Queue>();
private int maxQueueSize = DEF_MAX_QUEUE_SIZE_VAL;
private SimpleDateFormat formatter;
{
this.formatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
this.formatter.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
}
/**
* Method description
*
*
*
*/
@Override
public String id() {
return ID;
}
/**
* Method description
*
*
* @param settings
*
* @throws TigaseDBException
*/
@Override
public void init(Map<String, Object> settings) throws TigaseDBException {
super.init(settings);
Integer maxQueueSizeVal = (Integer) settings.get(MAX_QUEUE_SIZE_KEY);
if (maxQueueSizeVal != null) {
maxQueueSize = maxQueueSizeVal;
}
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*/
@Override
public void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings) {
if (session == null) {
return;
}
if (!session.isAuthorized()) {
try {
results.offer(session.getAuthState().getResponseMessage(packet,
"Session is not yet authorized.", false));
} catch (PacketErrorTypeException ex) {
log.log(Level.FINEST,
"ignoring packet from not authorized session which is already of type error");
}
return;
}
try {
StanzaType type = packet.getType();
switch (type) {
case set :
Element el = packet.getElement().getChild(MOBILE_EL_NAME);
String valueStr = el.getAttributeStaticStr("enable");
// if value is true queuing will be enabled
boolean value = (valueStr != null) && ("true".equals(valueStr) || "1".equals(
valueStr));
if (session.getSessionData(PRESENCE_QUEUE_KEY) == null) {
// session.putSessionData(QUEUE_KEY, new
// LinkedBlockingQueue<Packet>());
session.putSessionData(PRESENCE_QUEUE_KEY, new ConcurrentHashMap<JID, Packet>());
}
if (session.getSessionData(PACKET_QUEUE_KEY) == null) {
session.putSessionData(PACKET_QUEUE_KEY, new ArrayDeque<Packet>());
}
session.putSessionData(XMLNS, value);
results.offer(packet.okResult((Element) null, 0));
break;
default :
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Mobile processing type is incorrect", false));
}
} catch (PacketErrorTypeException ex) {
Logger.getLogger(MobileV3.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Method description
*
*
*
*/
@Override
public String[][] supElementNamePaths() {
return ELEMENT_PATHS;
}
/**
* Method description
*
*
*
*/
@Override
public String[] supNamespaces() {
return XMLNSS;
}
/**
* Method description
*
*
* @param session
*
*
*/
@Override
public Element[] supStreamFeatures(XMPPResourceConnection session) {
if (session == null) {
return null;
}
if (!session.isAuthorized()) {
return null;
}
return SUP_FEATURES;
}
/**
* Method description
*
*
* @param _packet
* @param sessionFromSM
* @param repo
* @param results
*/
@Override
@SuppressWarnings("unchecked")
public void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results) {
if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) ||
(results.size() == 0)) {
return;
}
Queue<Packet> prependResults = null;
for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) {
Packet res = it.next();
// check if packet contains destination
if ((res == null) || (res.getPacketTo() == null)) {
if (log.isLoggable(Level.FINEST)) {
log.finest("packet without destination");
}
continue;
}
// get resource connection for destination
XMPPResourceConnection session = sessionFromSM.getParentSession()
.getResourceForConnectionId(res.getPacketTo());
if (session == null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "no session for destination {0} for packet {1}",
new Object[] { res.getPacketTo().toString(),
res.toString() });
}
// if there is no session we should not queue
continue;
}
Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY);
Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY);
QueueState state = QueueState.need_flush;
if (!isQueueEnabled(session)) {
if ((presenceQueue == null && packetQueue == null)
|| (presenceQueue.isEmpty() && packetQueue.isEmpty())) {
continue;
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}",
new Object[] {presenceQueue.size(), packetQueue.size() });
}
} else {
state = filter(session, res, presenceQueue, packetQueue);
if (state == QueueState.queued) {
it.remove();
if (log.isLoggable(Level.FINEST))
log.log(Level.FINEST, "queue packet = {0}", res.toString());
if (presenceQueue.size() > maxQueueSize) {
state = QueueState.need_flush;
}
else if (packetQueue.size() > maxQueueSize)
state = QueueState.need_packet_flush;
}
}
switch (state) {
case need_flush:
prependResults = prependResultsThreadQueue.get();
if (prependResults == null) {
prependResults = new ArrayDeque<Packet>();
prependResultsThreadQueue.set(prependResults);
}
synchronized (presenceQueue) {
for (Packet p : presenceQueue.values()) {
prependResults.offer(p);
}
presenceQueue.clear();
}
case need_packet_flush:
if (prependResults == null) {
prependResults = prependResultsThreadQueue.get();
if (prependResults == null) {
prependResults = new ArrayDeque<Packet>();
prependResultsThreadQueue.set(prependResults);
}
}
synchronized (packetQueue) {
prependResults.addAll(packetQueue);
packetQueue.clear();
}
case queued:
break;
default:
break;
}
}
if (prependResults != null && !prependResults.isEmpty()) {
if (log.isLoggable(Level.FINEST))
log.log(Level.FINEST, "sending queued packets = {0}", prependResults.size());
prependResults.addAll(results);
results.clear();
results.addAll(prependResults);
prependResults.clear();
}
}
/**
* Method description
*
*
* @param session
* @param res
* @param presenceQueue
*
*
*/
private QueueState filter(XMPPResourceConnection session, Packet res, Map<JID,
Packet> presenceQueue, Queue<Packet> packetQueue) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "checking if packet should be queued {0}", res.toString());
}
if (res.getElemName() == MESSAGE_ELEM_NAME) {
List<Element> children = res.getElement().getChildren();
for (Element child : children) {
if (MessageCarbons.XMLNS.equals(child.getXMLNS())) {
Element delay = res.getElement().getChild(DELAY_ELEM_NAME, DELAY_XMLNS);
if (delay == null) {
delay = createDelayElem(session);
if (delay != null) {
Element forward = child.getChild("forward", "urn:xmpp:forward:0");
if (forward != null) {
Element msg = forward.getChild(MESSAGE_ELEM_NAME);
if (msg != null) {
msg.addChild(delay);
}
}
}
}
synchronized (packetQueue) {
packetQueue.offer(res);
}
return QueueState.queued;
}
}
return QueueState.need_packet_flush;
}
if (res.getElemName() != "presence") {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "ignoring packet, packet is not presence: {0}", res
.toString());
}
return QueueState.need_packet_flush;
}
StanzaType type = res.getType();
if ((type != null) && (type != StanzaType.unavailable) && (type != StanzaType
.available)) {
return QueueState.need_flush;
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "queuing packet {0}", res.toString());
}
Element delay = res.getElement().getChild(DELAY_ELEM_NAME, DELAY_XMLNS);
if (delay == null) {
delay = createDelayElem(session);
if (delay != null) {
res.getElement().addChild(delay);
}
}
synchronized (presenceQueue) {
presenceQueue.put(res.getStanzaFrom(), res);
}
return QueueState.queued;
}
private Element createDelayElem(XMPPResourceConnection session) {
String timestamp = null;
synchronized (formatter) {
timestamp = formatter.format(new Date());
}
try {
return new Element(DELAY_ELEM_NAME, new String[] { "xmlns", "from", "stamp" },
new String[] { DELAY_XMLNS, session.getBareJID().getDomain(), timestamp });
}
catch (NotAuthorizedException ex) {
return null;
}
}
/**
* Check if queuing is enabled
*
* @param session
*
*/
protected static boolean isQueueEnabled(XMPPResourceConnection session) {
Boolean enabled = (Boolean) session.getSessionData(XMLNS);
return (enabled != null) && enabled;
}
private static enum QueueState {
queued,
need_flush,
need_packet_flush
}
}
//~ Formatted in Tigase Code Convention on 13/03/16
|
package org.jasig.cas.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.jasig.cas.web.AbstractServletContextInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import javax.servlet.annotation.WebListener;
import javax.validation.constraints.NotNull;
import java.net.URI;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Initialize the CAS logging framework by updating the location of the log configuration file.
* @author Misagh Moayyed
* @since 4.1
*/
@WebListener
@Component("log4jInitialization")
public final class CasLoggerContextInitializer extends AbstractServletContextInitializer {
private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);
private static final Logger LOGGER = LoggerFactory.getLogger(CasLoggerContextInitializer.class);
@Value("${log4j.config.location:classpath:log4j2.xml}")
private final Resource logConfigurationFile;
/**
* Instantiates a new Cas logger context initializer.
*/
public CasLoggerContextInitializer() {
this.logConfigurationFile = null;
}
/**
* Instantiates a new Cas logger context initializer.
*
* @param logConfigurationFile the log configuration file
*/
public CasLoggerContextInitializer(@NotNull final Resource logConfigurationFile) {
this.logConfigurationFile = logConfigurationFile;
}
/**
* {@inheritDoc}
* Reinitialize the logger by updating the location for the logging config file.
*/
@Override
protected void initializeRootApplicationContext() {
if (this.logConfigurationFile == null || !this.logConfigurationFile.exists()) {
throw new RuntimeException("Log4j configuration file cannot be located");
}
try {
if (!INITIALIZED.get()) {
final LoggerContext context = (LoggerContext) LogManager.getContext(false);
final URI oldLocation = context.getConfigLocation();
final URI location = logConfigurationFile.getURI();
if (!location.equals(oldLocation)) {
context.setConfigLocation(location);
LOGGER.debug("Updated logging config file from [{}] to [{}]",
oldLocation != null ? oldLocation : "", location);
}
INITIALIZED.set(true);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
|
package gr.ntua.cslab.celar.server.daemon.rest;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Authz;
import com.sixsq.slipstream.persistence.DeploymentModule;
import com.sixsq.slipstream.persistence.ImageModule;
import com.sixsq.slipstream.persistence.ModuleParameter;
import com.sixsq.slipstream.persistence.Node;
import com.sixsq.slipstream.persistence.Target;
import gr.ntua.cslab.celar.server.daemon.Main;
import gr.ntua.cslab.celar.server.daemon.cache.ApplicationCache;
import gr.ntua.cslab.celar.server.daemon.cache.DeploymentCache;
import gr.ntua.cslab.celar.server.daemon.rest.beans.application.ApplicationInfo;
import gr.ntua.cslab.celar.server.daemon.rest.beans.application.ApplicationInfoList;
import gr.ntua.cslab.celar.server.daemon.rest.beans.deployment.DeploymentInfo;
import gr.ntua.cslab.celar.server.daemon.rest.beans.deployment.DeploymentInfoList;
import gr.ntua.cslab.celar.server.daemon.rest.beans.deployment.DeploymentStatus;
import gr.ntua.cslab.celar.slipstreamClient.SlipStreamSSService;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.ws.WebServiceException;
import org.apache.log4j.Logger;
import tools.CSARParser;
import tools.Parser;
/**
*
* @author Giannis Giannakopoulos
*/
@Path("/application/")
public class Application {
public Logger logger = Logger.getLogger(Application.class);
@GET
public ApplicationInfoList getApplications() {
return ApplicationCache.getApplications();
}
// IS calls
@GET
@Path("{id}/")
public ApplicationInfo getApplicationInfo(@PathParam("id") String id) {
ApplicationInfo info = new ApplicationInfo();
info.setId(id);
info.setDescription("Hello world :)");
info.setSubmitted(new Date().getTime());
info.setVersion("1.1.0");
return info;
}
@GET
@Path("search/")
public List<ApplicationInfo> searchApplicationsByProperty(
@DefaultValue("0") @QueryParam("submitted_start") long submittedStart,
@DefaultValue("0") @QueryParam("submitted_end") long submittedEnd,
@DefaultValue("Null") @QueryParam("description") String description,
@DefaultValue("0") @QueryParam("user_id") int userid,
@DefaultValue("Null") @QueryParam("module_name") String moduleName,
@DefaultValue("Null") @QueryParam("component_description") String componentDescription,
@DefaultValue("Null") @QueryParam("provided_resource_id") String providedResourceId) {
List<ApplicationInfo> list = new LinkedList<>();
list.add(new ApplicationInfo("ID1", submittedStart + 100, description, "1.0.0"));
list.add(new ApplicationInfo("ID2", submittedStart + 200, description, "1.2.0"));
list.add(new ApplicationInfo("ID3", submittedStart + 1000, description, "0.2.0"));
return list;
}
@GET
@Path("{id}/description/")
public ApplicationInfo getApplicationDescription(@PathParam("id") String id) {
ApplicationInfo info = new ApplicationInfo();
info.setId(id);
info.setDescription("This xml will be replaced by a TOSCA (or CSAR??) file...");
info.setSubmitted(new Date().getTime());
info.setVersion("1.1.0");
return info;
}
@POST
@Path("describe/")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public ApplicationInfo describe(@Context HttpServletRequest request, InputStream input) throws IOException, Exception {
// fetching csar file and store it to local fs
String filename = "/tmp/csar/" + System.currentTimeMillis() + ".csar";
byte[] buffer = new byte[1024];
OutputStream file = new FileOutputStream(filename);
int count, sum = 0;
while ((count = input.read(buffer)) != -1) {
sum+=count;
file.write(buffer, 0, count);
}
file.flush();
file.close();
Logger.getLogger(Application.class).info("Read CSAR file (" + sum + " bytes)");
input.close();
//create a Parser instance
Parser tc = new CSARParser(filename);
//application name and version
//String ssApplicationName = System.currentTimeMillis() + "-" + tc.getAppName();
String ssApplicationName = tc.getAppName();
logger.info("Application: " + tc.getAppName() + " v" + tc.getAppVersion());
String appName = Main.ssService.createApplication(ssApplicationName, tc.getAppVersion());
HashMap<String, Node> nodes = new HashMap<String, Node>();
//iterate through modules
for (String module : tc.getModules()) {
logger.info("\t" + module);
//module dependecies
logger.info("\t\tdepends on: " + tc.getModuleDependencies(module));
//iterate through components
for (String component : tc.getModuleComponents(module)) {
logger.info("\t\t" + component);
ImageModule imModule = new ImageModule(appName + "/" + component);
Authz auth = new Authz(Main.ssService.getUser(), imModule);
imModule.setAuthz(auth);
//component dependencies
logger.info("\t\t\tdepends on: " + tc.getComponentDependencies(component));
//component properties
Set<Target> targets = new HashSet<Target>();
for (Map.Entry prop : tc.getComponentProperties(component).entrySet()) {
//System.out.println("\t\t\t"+prop.getKey()+": "+prop.getValue());
if (prop.getKey().toString().equals("VMI")) {
imModule.setModuleReference(Main.ssService.getImageReference("ubuntu-12.04"));
} else if (prop.getKey().toString().equals("executeScript")) {
logger.info("script: " + prop.getValue().toString());
Target t = new Target(Target.EXECUTE_TARGET, prop.getValue().toString());
targets.add(t);
}
}
imModule.setTargets(targets);
for (ModuleParameter p : Main.ssService.baseParameters) {
imModule.setParameter(p);
}
Main.ssService.putModule(imModule);
nodes.put(imModule.getShortName(), new Node(imModule.getShortName(), imModule));
}
}
//add DeploymentModule
String name = appName + "/" + appName;
DeploymentModule deployment = new DeploymentModule(name);
Authz auth = new Authz(Main.ssService.getUser(), deployment);
deployment.setAuthz(auth);
logger.info("App Modules: " + nodes);
deployment.setNodes(nodes);
Main.ssService.putModule(deployment);
ApplicationInfo info = new ApplicationInfo();
info.setCsarFilePath(filename);
info.setId(UUID.randomUUID().toString());
info.setSubmitted(System.currentTimeMillis());
info.setVersion("1.0");
info.setDescription("No description for now dude!");
info.setSlipstreamName(name);
ApplicationCache.insertApplication(info);
return info;
}
@POST
@Path("{id}/deploy/")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public DeploymentInfo launchDeployment(@PathParam("id") String applicationId, InputStream input) throws IOException, InterruptedException, ValidationException {
// fetching csar file and store it to local fs
String filename = "/tmp/csar/" + System.currentTimeMillis() + ".csar";
byte[] buffer = new byte[1024];
OutputStream file = new FileOutputStream(filename);
int count, sum = 0;
while ((count = input.read(buffer)) != -1) {
sum+=count;
file.write(buffer, 0, count);
}
file.flush();
file.close();
Logger.getLogger(Application.class).info("Read CSAR file (" + sum + " bytes)");
input.close();
// parse TOSCA and give params to deployment
ApplicationInfo app = ApplicationCache.getApplicationById(applicationId);
Map<String, String> params = new HashMap<>();
String deploymentID = Main.ssService.launchApplication(app.getSlipstreamName(), params);
DeploymentInfo deployment = new DeploymentInfo();
deployment.setDeploymentID(deploymentID);
deployment.setApplication(app);
deployment.setStartTime(System.currentTimeMillis());
deployment.setEndTime(-1);
deployment.setStatus("BOOTSTRAPPING");
DeploymentCache.addDeployment(deployment);
return deployment;
}
@GET
@Path("{id}/deployments/")
public DeploymentInfoList getDeploymentsByApplicationId(@PathParam("id") String applicationId) {
List<DeploymentInfo> res = DeploymentCache.getDeploymentsByApplication(applicationId);
return new DeploymentInfoList(res);
}
}
|
package org.vitrivr.cineast.core.data.raw.images;
import org.vitrivr.cineast.core.data.raw.CacheableData;
import org.vitrivr.cineast.core.data.raw.bytes.ByteData;
import org.vitrivr.cineast.core.data.raw.bytes.CachedByteData;
import org.vitrivr.cineast.core.data.raw.CachedDataFactory;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.nio.file.Path;
/**
* The {@link CachedMultiImage} object is an immutable representation of a {@link BufferedImage} backed by a file cache. The data held
* by the {@link CachedMultiImage} object may be garbage collected if memory pressure builds up and must be re-created from the cache when accessed.
*
* A temporary cache file is created upon constructing the {@link CachedMultiImage} object and holds its content in case the in-memory
* representation gets garbage collected.
*
* @author Ralph Gasser
* @version 1.0
*
* @see MultiImage
* @see CacheableData
* @see CachedDataFactory
*/
public class CachedMultiImage extends CachedByteData implements MultiImage {
/** The width of the cached {@link MultiImage}. */
private final int width;
/** The height of the cached {@link MultiImage}. */
private final int height;
/** The height of the cached {@link MultiImage}. */
private final int type;
/** Soft reference to the thumbnail image. May be garbage collected under memory pressure. */
private SoftReference<BufferedImage> thumb;
/** Reference to the {@link CachedDataFactory} that created this {@link CachedMultiImage}. */
private final CachedDataFactory factory;
/**
* Constructor for {@link CachedMultiImage}.
*
* @param img {@link BufferedImage} to create a {@link CachedMultiImage} from.
* @param cacheFile The cache file in which to store {@link CachedMultiImage}.
* @throws IOException If creation of the cache file failed.
*/
public CachedMultiImage(BufferedImage img, Path cacheFile, CachedDataFactory factory) throws IOException {
this(img, null, cacheFile, factory);
}
/**
* Constructor for {@link CachedMultiImage}.
*
* @param img {@link BufferedImage} to create a {@link CachedMultiImage} from.
* @param thumb {@link BufferedImage} holding the thumbnail image.
* @param cacheFile The cache file in which to store {@link CachedMultiImage}.
* @throws IOException If creation of the cache file failed.
*/
public CachedMultiImage(BufferedImage img, BufferedImage thumb, Path cacheFile, CachedDataFactory factory) throws IOException {
super(toBytes(img), cacheFile, factory);
this.width = img.getWidth();
this.height = img.getHeight();
this.type = img.getType();
this.factory = factory;
if (thumb != null) {
this.thumb = new SoftReference<>(thumb);
} else {
this.thumb = new SoftReference<>(MultiImage.generateThumb(img));
}
}
/**
* Constructor for {@link CachedMultiImage}.
*
* @param colors The array holding the colors of the original, {@link BufferedImage}.
* @param width Width of the image.
* @param height Height of the image.
* @throws IOException If creation of the cache file failed.
*/
public CachedMultiImage(int[] colors, int width, int height, Path cacheFile, CachedDataFactory factory) throws IOException {
super(toBytes(colors, width, height), cacheFile, factory);
this.width = width;
this.height = height;
this.type = BufferedImage.TYPE_INT_RGB;
this.factory = factory;
final BufferedImage bimg = new BufferedImage(this.width, this.height, this.type);
bimg.setRGB(0, 0, this.width, this.height, colors, 0, this.width);
this.thumb = new SoftReference<>(MultiImage.generateThumb(bimg));
}
/**
* Getter for the thumbnail image of this {@link CachedMultiImage}. If the thumbnail image reference does not
* exist anymore, a new thumbnail image will be created from the raw data.
*
* Calling this method will cause the soft reference {@link CachedMultiImage#thumb} to be refreshed! However, there is
* no guarantee that the reference will still be around when invoking this or any other accessor the next time.
*
* @return The thumbnail image for this {@link CachedMultiImage}
*/
@Override
public BufferedImage getThumbnailImage() {
BufferedImage thumbnail = this.thumb.get();
if (thumbnail == null) {
thumbnail = MultiImage.generateThumb(this.getBufferedImage());
}
this.thumb = new SoftReference<>(thumbnail);
return thumbnail;
}
/**
* Getter for the colors array representing this {@link CachedMultiImage}.
*
* @return The thumbnail image for this {@link CachedMultiImage}
*/
@Override
public int[] getColors() {
final ByteBuffer buffer = this.buffer();
final int[] colors = new int[this.width * this.height];
for (int i=0; i<colors.length; i++) {
colors[i] = buffer.getInt();
}
return colors;
}
/**
* Getter for the {@link BufferedImage} held by this {@link CachedMultiImage}. The image is reconstructed from the the
* color array. See {@link CachedMultiImage#getColors()}
*
* @return The image held by this {@link CachedMultiImage}
*/
@Override
public BufferedImage getBufferedImage() {
int[] colors = getColors();
final BufferedImage image = new BufferedImage(this.width, this.height, this.type);
image.setRGB(0, 0, this.width, this.height, colors, 0, this.width);
return image;
}
/**
* Getter for the colors array representing the thumbnail of this {@link CachedMultiImage}.
*
* @return Color array
*/
@Override
public int[] getThumbnailColors() {
final BufferedImage thumb = this.getThumbnailImage();
return this.getThumbnailImage().getRGB(0, 0, thumb.getWidth(), thumb.getHeight(), null, 0, thumb.getWidth());
}
/**
* Getter for width value.
*
* @return Width of the {@link MultiImage}
*/
@Override
public int getWidth() {
return this.width;
}
/**
* Getter for height value.
*
* @return Height of the {@link MultiImage}
*/
@Override
public int getHeight() {
return this.height;
}
/**
* Getter for this {@link CachedDataFactory}.
*
* @return Factory that created this {@link InMemoryMultiImage}
*/
@Override
public CachedDataFactory factory() {
return this.factory;
}
/**
* Force clears all the {@link SoftReference}s associated with this {@link CachedMultiImage} object.
*/
@Override
public void clear() {
this.data.clear();
this.thumb.clear();
}
/**
* Converts the {@link BufferedImage} to a byte array representation.
*
* @param img The {@link BufferedImage} that should be converted.
* @return The byte array representing the {@link BufferedImage}
*/
private static byte[] toBytes(BufferedImage img) {
int[] colors = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
return toBytes(colors, img.getWidth(),img.getHeight());
}
/**
* Converts the int array holding the colors of a {@link BufferedImage} to a byte array representation.
*
* @param colors The int array holding the color values.
* @param width Width of the image.
* @param height Height of the image.
* @return The byte array representing the {@link BufferedImage}
*/
private static byte[] toBytes(int[] colors, int width, int height) {
final ByteBuffer data = ByteBuffer.allocate(width * height * 4);
for (int c : colors) {
data.putInt(c);
}
return data.array();
}
}
|
package arch.task.timer.model;
import javafx.beans.property.SimpleStringProperty;
public class UserFx {
private final SimpleStringProperty userName;
public UserFx(String userName){
this.userName = new SimpleStringProperty(userName);
}
public SimpleStringProperty getUserName() {
return userName;
}
}
|
package org.spine3.examples.todolist.client;
import com.google.protobuf.Timestamp;
import org.junit.jupiter.api.Test;
import org.spine3.examples.todolist.LabelColor;
import org.spine3.examples.todolist.LabelDetails;
import org.spine3.examples.todolist.TaskId;
import org.spine3.examples.todolist.TaskLabelId;
import org.spine3.examples.todolist.TaskPriority;
import org.spine3.examples.todolist.c.commands.AssignLabelToTask;
import org.spine3.examples.todolist.c.commands.CompleteTask;
import org.spine3.examples.todolist.c.commands.CreateBasicLabel;
import org.spine3.examples.todolist.c.commands.CreateBasicTask;
import org.spine3.examples.todolist.c.commands.CreateDraft;
import org.spine3.examples.todolist.c.commands.DeleteTask;
import org.spine3.examples.todolist.c.commands.RemoveLabelFromTask;
import org.spine3.examples.todolist.c.commands.ReopenTask;
import org.spine3.examples.todolist.c.commands.RestoreDeletedTask;
import org.spine3.examples.todolist.c.commands.UpdateLabelDetails;
import org.spine3.examples.todolist.c.commands.UpdateTaskDescription;
import org.spine3.examples.todolist.c.commands.UpdateTaskDueDate;
import org.spine3.examples.todolist.c.commands.UpdateTaskPriority;
import org.spine3.examples.todolist.q.projections.LabelledTasksView;
import org.spine3.examples.todolist.q.projections.TaskListView;
import org.spine3.examples.todolist.q.projections.TaskView;
import org.spine3.protobuf.Timestamps;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.DESCRIPTION;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.UPDATED_LABEL_TITLE;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.assignLabelToTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.completeTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.deleteTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.removeLabelFromTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.reopenTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.restoreDeletedTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskDescriptionInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskDueDateInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskPriorityInstance;
import static org.spine3.examples.todolist.testdata.TestTaskLabelCommandFactory.updateLabelDetailsInstance;
/**
* @author Illia Shepilov
*/
@SuppressWarnings({"OverlyCoupledClass", "ClassWithTooManyMethods"})
public class LabelledTasksViewClientTest extends CommandLineTodoClientTest {
@Test
public void obtain_labelled_tasks_view_when_handled_command_deleted_task_restored() throws Exception {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskLabelId labelId = createLabel.getLabelId();
final TaskId taskId = createTask.getId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final DeleteTask deleteTask = deleteTaskInstance(taskId);
client.delete(deleteTask);
final RestoreDeletedTask restoreDeletedTask = restoreDeletedTaskInstance(taskId);
client.restore(restoreDeletedTask);
final int expectedListSize = 1;
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
assertEquals(labelId, view.getLabelId());
}
@Test
public void obtain_empty_labelled_tasks_view_when_handled_command_deleted_task_restored_with_wrong_task_id() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskLabelId labelId = createLabel.getLabelId();
final TaskId taskId = createTask.getId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final DeleteTask deleteTask = deleteTaskInstance(taskId);
client.delete(deleteTask);
final RestoreDeletedTask restoreDeletedTask = restoreDeletedTaskInstance(getWrongTaskId());
client.restore(restoreDeletedTask);
final int expectedListSize = 1;
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
assertEquals(expectedListSize, tasksViewList.size());
final TaskListView taskListView = tasksViewList.get(0)
.getLabelledTasks();
final List<TaskView> taskViews = taskListView.getItemsList();
assertTrue(taskViews.isEmpty());
}
@Test
public void obtain_tasks_with_assigned_labels_from_labelled_tasks_view() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final int expectedListSize = 1;
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
assertEquals(labelId, view.getLabelId());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_assign_label_to_task_with_different_task_ids() {
final CreateBasicTask firstTask = createBasicTask();
client.create(firstTask);
final CreateBasicTask secondTask = createBasicTask();
client.create(secondTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskLabelId labelId = createLabel.getLabelId();
final TaskId firstTaskId = firstTask.getId();
final TaskId secondTaskId = secondTask.getId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(secondTaskId, labelId);
client.assignLabel(assignLabelToTask);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView taskView = taskViews.get(0);
assertNotEquals(firstTaskId, taskView.getId());
assertEquals(secondTaskId, taskView.getId());
assertEquals(labelId, taskView.getLabelId());
}
@Test
public void obtain_updated_task_description_from_labelled_tasks_view_when_handled_command_update_task_description() {
final TaskView view = obtainViewWhenHandledCommandUpdateTaskDescription(UPDATED_TASK_DESCRIPTION, true);
assertEquals(UPDATED_TASK_DESCRIPTION, view.getDescription());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_update_task_description_with_wrong_task_id() {
final TaskView view = obtainViewWhenHandledCommandUpdateTaskDescription(UPDATED_TASK_DESCRIPTION, false);
final String actualDescription = view.getDescription();
assertNotEquals(UPDATED_TASK_DESCRIPTION, actualDescription);
assertEquals(DESCRIPTION, actualDescription);
}
@Test
public void obtain_updated_task_priority_from_labelled_tasks_view_when_handled_command_update_task_priority() {
final TaskPriority newPriority = TaskPriority.HIGH;
final TaskView view = obtainViewWhenHandledCommandUpdateTaskPriority(newPriority, true);
assertEquals(newPriority, view.getPriority());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_update_task_priority_with_wrong_task_id() {
final TaskPriority newPriority = TaskPriority.HIGH;
final TaskView view = obtainViewWhenHandledCommandUpdateTaskPriority(newPriority, false);
assertNotEquals(newPriority, view.getPriority());
}
@Test
public void obtain_updated_task_due_date_from_labelled_tasks_view_when_handled_command_update_task_due_date() {
final Timestamp newDueDate = Timestamps.getCurrentTime();
final TaskView view = obtainViewWhenHandledCommandUpdateTaskDueDate(newDueDate, true);
assertEquals(newDueDate, view.getDueDate());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_update_task_due_date_with_wrong_task_id() {
final Timestamp newDueDate = Timestamps.getCurrentTime();
final TaskView view = obtainViewWhenHandledCommandUpdateTaskDueDate(newDueDate, false);
assertNotEquals(newDueDate, view.getDueDate());
}
@Test
public void obtain_empty_labelled_tasks_view_when_handled_command_remove_label_from_task() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final RemoveLabelFromTask removeLabelFromTask = removeLabelFromTaskInstance(taskId, labelId);
client.removeLabel(removeLabelFromTask);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertTrue(taskViews.isEmpty());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_remove_label_from_task_with_wrong_label_id() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final RemoveLabelFromTask removeLabelFromTask = removeLabelFromTaskInstance(taskId, getWrongTaskLabelId());
client.removeLabel(removeLabelFromTask);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
int expectedListSize = 2;
assertEquals(expectedListSize, tasksViewList.size());
final LabelledTasksView labelledTasksView = getLabelledTasksView(tasksViewList);
final List<TaskView> taskViews = labelledTasksView.getLabelledTasks()
.getItemsList();
expectedListSize = 1;
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
assertFalse(taskViews.isEmpty());
}
@Test
public void obtain_empty_labelled_tasks_view_when_handled_command_delete_task() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskLabelId labelId = createLabel.getLabelId();
final TaskId taskId = createTask.getId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final DeleteTask deleteTask = deleteTaskInstance(taskId);
client.delete(deleteTask);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, labelledTasksView.size());
final List<TaskView> taskViews = labelledTasksView.get(0)
.getLabelledTasks()
.getItemsList();
assertTrue(taskViews.isEmpty());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_delete_task_with_wrong_task_id() {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskLabelId labelId = createLabel.getLabelId();
final TaskId taskId = createTask.getId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final DeleteTask deleteTask = deleteTaskInstance(getWrongTaskId());
client.delete(deleteTask);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, labelledTasksView.size());
final List<TaskView> taskViews = labelledTasksView.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_complete_task() {
final TaskView view = obtainViewWhenHandledCommandCompleteTask(true);
assertTrue(view.getCompleted());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_complete_task_with_wrong_task_id() {
final TaskView view = obtainViewWhenHandledCommandCompleteTask(false);
assertFalse(view.getCompleted());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_reopen_task() {
final TaskView view = obtainViewWhenHandledCommandReopenTask(true);
assertFalse(view.getCompleted());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_reopen_task_with_wrong_task_id() {
final TaskView view = obtainViewWhenHandledCommandReopenTask(false);
assertTrue(view.getCompleted());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_update_label_details() {
final LabelColor updatedColor = LabelColor.BLUE;
final LabelledTasksView view = obtainViewWhenHandledCommandUpdateLabelDetails(updatedColor,
UPDATED_LABEL_TITLE,
true);
assertEquals(UPDATED_LABEL_TITLE, view.getLabelTitle());
final String expectedColor = "#0000ff";
assertEquals(expectedColor, view.getLabelColor());
}
@Test
public void obtain_labelled_tasks_view_when_handled_command_update_label_details_with_wrong_task_id() {
final LabelColor updatedColor = LabelColor.BLUE;
final LabelledTasksView view = obtainViewWhenHandledCommandUpdateLabelDetails(updatedColor,
UPDATED_LABEL_TITLE,
false);
assertNotEquals(UPDATED_LABEL_TITLE, view.getLabelTitle());
final String expectedColor = "#0000ff";
assertNotEquals(expectedColor, view.getLabelColor());
}
@Test
public void obtain_empty_labelled_tasks_view_when_handled_command_create_draft() {
final CreateDraft createDraft = createDraft();
client.create(createDraft);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
assertTrue(labelledTasksView.isEmpty());
}
@Test
public void obtain_empty_labelled_tasks_view_when_handled_command_create_task() {
final CreateBasicTask createBasicTask = createBasicTask();
client.create(createBasicTask);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
assertTrue(labelledTasksView.isEmpty());
}
private static LabelledTasksView getLabelledTasksView(List<LabelledTasksView> tasksViewList) {
LabelledTasksView result = LabelledTasksView.getDefaultInstance();
for (LabelledTasksView labelledView : tasksViewList) {
final boolean isEmpty = labelledView.getLabelId()
.getValue()
.isEmpty();
if (!isEmpty) {
result = labelledView;
}
}
return result;
}
private LabelledTasksView obtainViewWhenHandledCommandUpdateLabelDetails(LabelColor updatedColor,
String updatedTitle,
boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final LabelDetails detailsWithCorrectId = LabelDetails.newBuilder()
.setColor(LabelColor.GRAY)
.setTitle(createLabel.getLabelTitle())
.build();
final LabelDetails newLabelDetails = LabelDetails.newBuilder()
.setColor(updatedColor)
.setTitle(updatedTitle)
.build();
final LabelDetails previousLabelDetails =
isCorrectId ? detailsWithCorrectId : LabelDetails.getDefaultInstance();
final TaskLabelId updatedLabelId = isCorrectId ? labelId : getWrongTaskLabelId();
final UpdateLabelDetails updateLabelDetails =
updateLabelDetailsInstance(updatedLabelId, previousLabelDetails, newLabelDetails);
client.update(updateLabelDetails);
final List<LabelledTasksView> labelledTasksViewList = client.getLabelledTasksView();
final int correctIdExpectedSize = 1;
final int incorrectIdExpectedSize = 2;
final int expectedListSize = isCorrectId ? correctIdExpectedSize : incorrectIdExpectedSize;
assertEquals(expectedListSize, labelledTasksViewList.size());
final LabelledTasksView view = getLabelledTasksView(labelledTasksViewList);
assertEquals(labelId, view.getLabelId());
return view;
}
private TaskView obtainViewWhenHandledCommandReopenTask(boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
final TaskId createdTaskId = createTask.getId();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final CompleteTask completeTask = completeTaskInstance(createdTaskId);
client.complete(completeTask);
final TaskId reopenedTaskId = isCorrectId ? createdTaskId : getWrongTaskId();
final ReopenTask reopenTask = reopenTaskInstance(reopenedTaskId);
client.reopen(reopenTask);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, labelledTasksView.size());
final List<TaskView> taskViews = labelledTasksView.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
return view;
}
private TaskView obtainViewWhenHandledCommandCompleteTask(boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
final TaskId createdTaskId = createTask.getId();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final TaskId completedTaskId = isCorrectId ? createdTaskId : getWrongTaskId();
final CompleteTask completeTask = completeTaskInstance(completedTaskId);
client.complete(completeTask);
final List<LabelledTasksView> labelledTasksView = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, labelledTasksView.size());
final List<TaskView> taskViews = labelledTasksView.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(taskId, view.getId());
return view;
}
private TaskView obtainViewWhenHandledCommandUpdateTaskDescription(String newDescription, boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
final TaskId createdTaskId = createTask.getId();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final TaskId updatedTaskId = isCorrectId ? createdTaskId : getWrongTaskId();
final UpdateTaskDescription updateTaskDescription =
updateTaskDescriptionInstance(updatedTaskId, createTask.getDescription(), newDescription);
client.update(updateTaskDescription);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, tasksViewList.get(0)
.getLabelledTasks()
.getItemsCount());
final TaskView view = tasksViewList.get(0)
.getLabelledTasks()
.getItems(0);
assertEquals(labelId, view.getLabelId());
assertEquals(taskId, view.getId());
return view;
}
private TaskView obtainViewWhenHandledCommandUpdateTaskPriority(TaskPriority priority, boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
final TaskId createdTaskId = createTask.getId();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final int expectedListSize = 1;
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(createdTaskId, createLabel.getLabelId());
client.assignLabel(assignLabelToTask);
final TaskId updatedTaskId = isCorrectId ? createdTaskId : getWrongTaskId();
final UpdateTaskPriority updateTaskPriority =
updateTaskPriorityInstance(updatedTaskId, TaskPriority.TP_UNDEFINED, priority);
client.update(updateTaskPriority);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(createLabel.getLabelId(), view.getLabelId());
assertEquals(createdTaskId, view.getId());
return view;
}
private TaskView obtainViewWhenHandledCommandUpdateTaskDueDate(Timestamp newDueDate, boolean isCorrectId) {
final CreateBasicTask createTask = createBasicTask();
final TaskId createdTaskId = createTask.getId();
client.create(createTask);
final CreateBasicLabel createLabel = createBasicLabel();
client.create(createLabel);
final TaskId taskId = createTask.getId();
final TaskLabelId labelId = createLabel.getLabelId();
final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId);
client.assignLabel(assignLabelToTask);
final TaskId updatedTaskId = isCorrectId ? createdTaskId : getWrongTaskId();
final Timestamp previousDueDate = Timestamp.getDefaultInstance();
final UpdateTaskDueDate updateTaskDueDate = updateTaskDueDateInstance(updatedTaskId, previousDueDate, newDueDate);
client.update(updateTaskDueDate);
final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView();
final int expectedListSize = 1;
assertEquals(expectedListSize, tasksViewList.size());
final List<TaskView> taskViews = tasksViewList.get(0)
.getLabelledTasks()
.getItemsList();
assertEquals(expectedListSize, taskViews.size());
final TaskView view = taskViews.get(0);
assertEquals(labelId, view.getLabelId());
assertEquals(taskId, view.getId());
return view;
}
}
|
package ro.msg.cm.util;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import ro.msg.cm.model.Candidate;
import ro.msg.cm.model.Education;
import ro.msg.cm.model.StartYearProperties;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;
public class CandidateUtilDetermineYearBasedOnDurationTest {
private static CandidateUtils updateUniversityYearUtils;
@BeforeClass
public static void setUpClass() {
StartYearProperties underTest = new StartYearProperties();
underTest.setStartYearDate("10-01");
updateUniversityYearUtils = new CandidateUtils(underTest);
}
@Test
public void oneAndHalfYearDifference() {
Candidate candidate = getCandidate(1, 4, "2015-10-15");
setToday("2017-04-15");
Assert.assertEquals(2, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneAndHalfYearDifferenceWithDuration() {
Candidate candidate = getCandidate(3, 3, "2015-11-13");
setToday("2017-05-13");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneAndHalfYearDifferenceWithAddedDateOnNewUniversityYear() {
Candidate candidate = getCandidate(1, 4, "2015-10-01");
setToday("2017-04-01");
Assert.assertEquals(2, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneAndHalfYearDifferenceWithAddedDateOnNewUniversityYearWithDuration() {
Candidate candidate = getCandidate(4, 4, "2015-10-01");
setToday("2017-04-01");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneAndHalfYearDifferenceWithBonusYear() {
Candidate candidate = getCandidate(1, 4, "2015-09-18");
setToday("2017-04-18");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneAndHalfYearDifferenceWithBonusYearWithDuration() {
Candidate candidate = getCandidate(3, 4, "2015-08-17");
setToday("2017-03-17");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneYearDifference() {
Candidate candidate = getCandidate(1, 4, "2015-09-20");
setToday("2016-09-20");
Assert.assertEquals(2, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneYearDifferenceWithAddedDateOnNewUniversityYear() {
Candidate candidate = getCandidate(2, 4, "2015-10-01");
setToday("2016-10-01");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneYearDifferenceWithDuration() {
Candidate candidate = getCandidate(3, 3, "2015-09-07");
setToday("2016-09-07");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithNewYear() {
Candidate candidate = getCandidate(2, 4, "2015-09-05");
setToday("2016-03-05");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithoutNewYear() {
Candidate candidate = getCandidate(3, 4, "2015-04-08");
setToday("2015-10-08");
Assert.assertEquals(4, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithNewYearWithDuration() {
Candidate candidate = getCandidate(3, 3, "2015-08-01");
setToday("2016-02-01");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithoutNewYearWithDuration() {
Candidate candidate = getCandidate(5, 5, "2015-06-06");
setToday("2015-12-06");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithNewYearNoChange() {
Candidate candidate = getCandidate(3, 3, "2015-11-01");
setToday("2016-05-01");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithNewYearWithAddedDateOnNewUniversityYearNoChange() {
Candidate candidate = getCandidate(3, 3, "2015-10-01");
setToday("2016-04-01");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void halfYearDifferenceWithoutNewYearNoChange() {
Candidate candidate = getCandidate(3, 3, "2015-01-19");
setToday("2015-07-19");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneDayDifference() {
Candidate candidate = getCandidate(3, 4, "2015-09-30");
setToday("2015-10-01");
Assert.assertEquals(4, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneDayDifferenceWithDuration() {
Candidate candidate = getCandidate(4, 4, "2015-09-30");
setToday("2015-10-01");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneDayDifferenceNoChange() {
Candidate candidate = getCandidate(3, 4, "2015-09-28");
setToday("2015-09-29");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneDayDifferenceWithNewYearsNoChange() {
Candidate candidate = getCandidate(3, 4, "2015-12-31");
setToday("2016-01-01");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void oneDayDifferenceWithAddedDateOnNewUniversityYearNoChange() {
Candidate candidate = getCandidate(3, 4, "2015-10-01");
setToday("2015-10-02");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYear_2018_01_29() {
Candidate candidate = getCandidate(1, 4, "2015-09-23");
setToday("2018-01-29");
Assert.assertEquals(4, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYearAccordingToStudyDuration_2018_01_29() {
Candidate candidate = getCandidate(3, 2, "2016-10-25");
setToday("2018-01-29");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldNotModifyTheStudyYear_2018_01_29() {
Candidate candidate = getCandidate(2, 3, "2017-01-02");
setToday("2018-01-29");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYear_2017_08_23() {
Candidate candidate = getCandidate(1, 4, "2015-09-23");
setToday("2017-08-23");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYearAccordingToStudyDuration_2017_08_23() {
Candidate candidate = getCandidate(3, 2, "2016-10-25");
setToday("2017-08-23");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldNotModifyTheStudyYear_2017_08_23() {
Candidate candidate = getCandidate(2, 3, "2017-01-02");
setToday("2017-08-23");
Assert.assertEquals(2, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYear_2017_10_30() {
Candidate candidate = getCandidate(1, 4, "2015-09-23");
setToday("2017-10-30");
Assert.assertEquals(4, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldModifyTheStudyYearAccordingToStudyDuration_2017_10_30() {
Candidate candidate = getCandidate(3, 2, "2016-10-25");
setToday("2017-10-30");
Assert.assertEquals(-1, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
@Test
public void shouldNotModifyTheStudyYear_2017_10_30() {
Candidate candidate = getCandidate(2, 3, "2017-01-02");
setToday("2017-10-30");
Assert.assertEquals(3, updateUniversityYearUtils.determineYearBasedOnDuration(candidate));
}
private Candidate getCandidate(int OriginalStudyYear, int duration, String yearYMD) {
Candidate candidate = new Candidate();
candidate.setDateOfAdding(Date.from(LocalDate.parse(yearYMD).atStartOfDay().toInstant(ZoneOffset.UTC)));
candidate.setOriginalStudyYear(OriginalStudyYear);
candidate.setEducation(new Education());
candidate.getEducation().setDuration(duration);
return candidate;
}
private void setToday(String yearYMD) {
updateUniversityYearUtils.setGivenDate(Date.from(LocalDate.parse(yearYMD).atStartOfDay().toInstant(ZoneOffset.UTC)));
}
}
|
package imagej.data.display;
import imagej.ImageJ;
import imagej.data.display.event.MouseCursorEvent;
import imagej.data.display.event.PanZoomEvent;
import imagej.event.EventService;
import imagej.ext.MouseCursor;
import imagej.log.LogService;
import imagej.util.IntCoords;
import imagej.util.IntRect;
import imagej.util.RealCoords;
import imagej.util.RealRect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* The DefaultImageCanvas maintains a viewport, a zoom scale and a center
* coordinate that it uses to map viewport pixels to display coordinates. It
* also maintains an abstract mouse cursor.
* <p>
* The canvas sends a {@link PanZoomEvent} whenever it is panned or zoomed. It
* sends a {@link MouseCursorEvent} whenever the mouse cursor changes.
* </p>
*
* @author Lee Kamentsky
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class DefaultImageCanvas implements ImageCanvas {
private static final int MIN_ALLOWED_VIEW_SIZE = 25;
private static double maxZoom;
private static double[] defaultZooms;
static {
final List<Double> midLevelZooms = new ArrayList<Double>();
midLevelZooms.add(1 / 32d);
midLevelZooms.add(1 / 24d);
midLevelZooms.add(1 / 16d);
midLevelZooms.add(1 / 12d);
midLevelZooms.add(1 / 8d);
midLevelZooms.add(1 / 6d);
midLevelZooms.add(1 / 4d);
midLevelZooms.add(1 / 3d);
midLevelZooms.add(1 / 2d);
midLevelZooms.add(3 / 4d);
midLevelZooms.add(1d);
midLevelZooms.add(1.5d);
midLevelZooms.add(2d);
midLevelZooms.add(3d);
midLevelZooms.add(4d);
midLevelZooms.add(6d);
midLevelZooms.add(8d);
midLevelZooms.add(12d);
midLevelZooms.add(16d);
midLevelZooms.add(24d);
midLevelZooms.add(32d);
final int EXTRA_ZOOMS = 25;
final List<Double> loZooms = new ArrayList<Double>();
double prevDenom = 1 / midLevelZooms.get(0);
for (int i = 0; i < EXTRA_ZOOMS; i++) {
final double newDenom = prevDenom + 16;
loZooms.add(1 / newDenom);
prevDenom = newDenom;
}
Collections.reverse(loZooms);
final List<Double> hiZooms = new ArrayList<Double>();
double prevNumer = midLevelZooms.get(midLevelZooms.size() - 1);
for (int i = 0; i < EXTRA_ZOOMS; i++) {
final double newNumer = prevNumer + 16;
hiZooms.add(newNumer / 1);
prevNumer = newNumer;
}
final List<Double> combinedZoomLevels = new ArrayList<Double>();
combinedZoomLevels.addAll(loZooms);
combinedZoomLevels.addAll(midLevelZooms);
combinedZoomLevels.addAll(hiZooms);
defaultZooms = new double[combinedZoomLevels.size()];
for (int i = 0; i < defaultZooms.length; i++)
defaultZooms[i] = combinedZoomLevels.get(i);
maxZoom = hiZooms.get(hiZooms.size() - 1);
}
/** The canvas's display. */
private final ImageDisplay display;
/** The size of the viewport. */
private final IntCoords viewportSize;
/** The standard zoom levels for the canvas. */
private final double[] zoomLevels;
/** Initial scale factor, for resetting zoom. */
private double initialScale = 1;
/** The current scale factor. */
private double scale = 1.0;
private MouseCursor mouseCursor;
private RealCoords panCenter;
public DefaultImageCanvas(final ImageDisplay display) {
this.display = display;
mouseCursor = MouseCursor.DEFAULT;
viewportSize = new IntCoords(100, 100);
zoomLevels = validatedZoomLevels(defaultZooms);
}
// -- ImageCanvas methods --
@Override
public ImageDisplay getDisplay() {
return display;
}
@Override
public int getViewportWidth() {
return viewportSize.x;
}
@Override
public int getViewportHeight() {
return viewportSize.y;
}
@Override
public void setViewportSize(final int width, final int height) {
viewportSize.x = width;
viewportSize.y = height;
}
@Override
public boolean isInImage(final IntCoords point) {
final RealCoords dataCoords = panelToDataCoords(point);
return getDisplay().getPlaneExtents().contains(dataCoords);
}
@Override
public RealCoords panelToDataCoords(final IntCoords panelCoords) {
final double dataX = panelCoords.x / getZoomFactor() + getLeftImageX();
final double dataY = panelCoords.y / getZoomFactor() + getTopImageY();
return new RealCoords(dataX, dataY);
}
@Override
public IntCoords dataToPanelCoords(final RealCoords dataCoords) {
final int panelX =
(int) Math.round(getZoomFactor() * (dataCoords.x - getLeftImageX()));
final int panelY =
(int) Math.round(getZoomFactor() * (dataCoords.y - getTopImageY()));
return new IntCoords(panelX, panelY);
}
@Override
public MouseCursor getCursor() {
return mouseCursor;
}
@Override
public void setCursor(final MouseCursor cursor) {
mouseCursor = cursor;
final EventService eventService = getEventService();
if (eventService != null) eventService.publish(new MouseCursorEvent(this));
}
// -- Pannable methods --
@Override
public RealCoords getPanCenter() {
if (panCenter == null) {
panReset();
}
if (panCenter == null) throw new IllegalStateException();
return new RealCoords(panCenter.x, panCenter.y);
}
@Override
public void setPanCenter(final RealCoords center) {
if (panCenter == null) {
panCenter = new RealCoords(center.x, center.y);
}
else {
panCenter.x = center.x;
panCenter.y = center.y;
}
publishPanZoomEvent();
}
@Override
public void setPanCenter(final IntCoords center) {
setPanCenter(panelToDataCoords(center));
}
@Override
public void pan(final RealCoords delta) {
final double centerX = getPanCenter().x + delta.x;
final double centerY = getPanCenter().y + delta.y;
setPanCenter(new RealCoords(centerX, centerY));
}
@Override
public void pan(final IntCoords delta) {
final double centerX = getPanCenter().x + delta.x / getZoomFactor();
final double centerY = getPanCenter().y + delta.y / getZoomFactor();
setPanCenter(new RealCoords(centerX, centerY));
}
@Override
public void panReset() {
final RealRect extents = getDisplay().getPlaneExtents();
final double centerX = extents.x + extents.width / 2;
final double centerY = extents.y + extents.height / 2;
setPanCenter(new RealCoords(centerX, centerY));
}
// -- Zoomable methods --
@Override
public void setZoom(final double factor) {
final double desiredScale = factor == 0 ? initialScale : factor;
if (scaleOutOfBounds(desiredScale) || desiredScale == getZoomFactor()) {
return;
}
scale = factor;
publishPanZoomEvent();
}
@Override
public void setZoom(final double factor, final RealCoords center) {
final double desiredScale = factor == 0 ? initialScale : factor;
if (scaleOutOfBounds(desiredScale)) return;
if (panCenter == null) {
panCenter = new RealCoords(center.x, center.y);
}
else {
panCenter.x = center.x;
panCenter.y = center.y;
}
scale = desiredScale;
publishPanZoomEvent();
}
@Override
public void setZoom(final double factor, final IntCoords center) {
setZoom(factor, panelToDataCoords(center));
}
@Override
public void setZoomAndCenter(final double factor) {
final double x = getViewportWidth() / getZoomFactor() / 2;
final double y = getViewportHeight() / getZoomFactor() / 2;
setZoom(factor, new RealCoords(x, y));
}
@Override
public void zoomIn() {
final double newScale = nextLargerZoom(zoomLevels, getZoomFactor());
setZoom(newScale);
}
@Override
public void zoomIn(final RealCoords center) {
final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor());
setZoom(desiredScale, center);
}
@Override
public void zoomIn(final IntCoords center) {
final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor());
setZoom(desiredScale, center);
}
@Override
public void zoomOut() {
final double desiredScale = nextSmallerZoom(zoomLevels, getZoomFactor());
setZoom(desiredScale);
}
@Override
public void zoomOut(final RealCoords center) {
final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor());
setZoom(newScale, center);
}
@Override
public void zoomOut(final IntCoords center) {
final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor());
setZoom(newScale, center);
}
@Override
public void zoomToFit(final IntRect viewportBox) {
final IntCoords topLeft = viewportBox.getTopLeft();
final IntCoords bottomRight = viewportBox.getBottomRight();
final RealCoords dataTopLeft = panelToDataCoords(topLeft);
final RealCoords dataBottomRight = panelToDataCoords(bottomRight);
final double newCenterX = Math.abs(dataBottomRight.x + dataTopLeft.x) / 2;
final double newCenterY = Math.abs(dataBottomRight.y + dataTopLeft.y) / 2;
final double dataSizeX = Math.abs(dataBottomRight.x - dataTopLeft.x);
final double dataSizeY = Math.abs(dataBottomRight.y - dataTopLeft.y);
final double xZoom = getViewportWidth() / dataSizeX;
final double yZoom = getViewportHeight() / dataSizeY;
final double factor = Math.min(xZoom, yZoom);
setZoom(factor, new RealCoords(newCenterX, newCenterY));
}
@Override
public void zoomToFit(final RealRect viewportBox) {
final double newCenterX = (viewportBox.x + viewportBox.width / 2);
final double newCenterY = (viewportBox.y + viewportBox.height / 2);
final double minScale =
Math.min(getViewportWidth() / viewportBox.width, getViewportHeight() /
viewportBox.height);
setZoom(minScale, new RealCoords(newCenterX, newCenterY));
}
@Override
public double getZoomFactor() {
return this.scale;
}
@Override
public double getInitialScale() {
return initialScale;
}
@Override
public void setInitialScale(final double zoomFactor) {
if (zoomFactor <= 0) {
throw new IllegalArgumentException("Initial scale must be > 0");
}
this.initialScale = zoomFactor;
}
@Override
public double getBestZoomLevel(final double fractionalScale) {
final double[] levels = defaultZooms;
final int zoomIndex = lookupZoomIndex(levels, fractionalScale);
if (zoomIndex != -1) return levels[zoomIndex];
return nextSmallerZoom(levels, fractionalScale);
}
// -- Helper methods --
private void publishPanZoomEvent() {
final ImageJ context = getDisplay().getContext();
if (context == null) return;
final EventService eventService = getEventService();
if (eventService != null) eventService.publish(new PanZoomEvent(this));
}
// -- Helper methods --
/** Gets the log to which messages should be sent. */
private LogService getLog() {
final ImageJ context = display.getContext();
if (context == null) return null;
return context.getService(LogService.class);
}
/** Gets the service to which events should be published. */
private EventService getEventService() {
final ImageJ context = display.getContext();
if (context == null) return null;
return context.getService(EventService.class);
}
/**
* Gets the coordinate of the left edge of the viewport in <em>data</em>
* space.
*/
private double getLeftImageX() {
final double viewportImageWidth = getViewportWidth() / getZoomFactor();
return getPanCenter().x - viewportImageWidth / 2;
}
/**
* Gets the coordinate of the top edge of the viewport in <em>data</em> space.
*/
private double getTopImageY() {
final double viewportImageHeight = getViewportHeight() / getZoomFactor();
return getPanCenter().y - viewportImageHeight / 2;
}
/** Checks whether the given scale is out of bounds. */
private boolean scaleOutOfBounds(final double desiredScale) {
if (desiredScale <= 0) {
final LogService log = getLog();
if (log != null) log.warn("**** BAD SCALE: " + desiredScale + " ****");
return true;
}
if (desiredScale > maxZoom) return true;
// check if trying to zoom out too far
if (desiredScale < getZoomFactor()) {
// get boundaries of the plane in panel coordinates
final RealRect planeExtents = getDisplay().getPlaneExtents();
final IntCoords nearCornerPanel =
dataToPanelCoords(new RealCoords(planeExtents.x, planeExtents.y));
final IntCoords farCornerPanel =
dataToPanelCoords(new RealCoords(planeExtents.x + planeExtents.width,
planeExtents.y + planeExtents.height));
// if boundaries take up less than min allowed pixels in either dimension
final int panelX = farCornerPanel.x - nearCornerPanel.x;
final int panelY = farCornerPanel.y - nearCornerPanel.y;
if (panelX < MIN_ALLOWED_VIEW_SIZE && panelY < MIN_ALLOWED_VIEW_SIZE) {
return true;
}
}
return false;
}
private static double nextSmallerZoom(final double[] zoomLevels,
final double currScale)
{
final int index = Arrays.binarySearch(zoomLevels, currScale);
int nextIndex;
if (index >= 0) nextIndex = index - 1;
else nextIndex = -(index + 1) - 1;
if (nextIndex < 0) nextIndex = 0;
if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1;
return zoomLevels[nextIndex];
}
private static double nextLargerZoom(final double[] zoomLevels,
final double currScale)
{
final int index = Arrays.binarySearch(zoomLevels, currScale);
int nextIndex;
if (index >= 0) nextIndex = index + 1;
else nextIndex = -(index + 1);
if (nextIndex < 0) nextIndex = 0;
if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1;
return zoomLevels[nextIndex];
}
private static double[] validatedZoomLevels(final double[] levels) {
final double[] validatedLevels = levels.clone();
Arrays.sort(validatedLevels);
if (validatedLevels.length == 0) {
throw new IllegalArgumentException("given zoom level array is empty");
}
double prevEntry = validatedLevels[0];
if (prevEntry <= 0) {
throw new IllegalArgumentException(
"zoom level array contains nonpositive entries");
}
for (int i = 1; i < validatedLevels.length; i++) {
final double currEntry = validatedLevels[i];
if (currEntry == prevEntry) {
throw new IllegalArgumentException(
"zoom level array contains duplicate entries");
}
prevEntry = currEntry;
}
return validatedLevels;
}
/**
* Unfortunately, we can't rely on Java's binary search since we're using
* doubles and rounding errors could cause problems. So we write our own that
* searches zooms avoiding rounding problems.
*/
private static int lookupZoomIndex(final double[] levels,
final double requestedZoom)
{
int lo = 0;
int hi = levels.length - 1;
do {
final int mid = (lo + hi) / 2;
final double possibleZoom = levels[mid];
if (Math.abs(requestedZoom - possibleZoom) < 0.00001) return mid;
if (requestedZoom < possibleZoom) hi = mid - 1;
else lo = mid + 1;
}
while (hi >= lo);
return -1;
}
}
|
package de.gurkenlabs.litiengine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Map;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset;
import de.gurkenlabs.litiengine.graphics.particles.xml.EmitterData;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
import de.gurkenlabs.litiengine.util.io.XmlUtilities;
@XmlRootElement(name = "game")
public class GameFile implements Serializable {
private static final Logger log = Logger.getLogger(GameFile.class.getName());
public static final String FILE_EXTENSION = "env";
public static final float CURRENT_VERSION = 1.0f;
private static final long serialVersionUID = -2101786184799276518L;
@XmlAttribute(name = "version")
private float version;
@XmlElementWrapper(name = "maps")
@XmlElement(name = "map")
private List<Map> maps;
@XmlElementWrapper(name = "spriteSheets")
@XmlElement(name = "sprite")
private List<SpriteSheetInfo> spriteSheets;
@XmlElementWrapper(name = "tilesets")
@XmlElement(name = "tileset")
private List<Tileset> tilesets;
@XmlElementWrapper(name = "emitters")
@XmlElement(name = "emitter")
private List<EmitterData> emitters;
@XmlElementWrapper(name = "blueprints")
@XmlElement(name = "blueprint")
private List<Blueprint> blueprints;
public GameFile() {
this.spriteSheets = new ArrayList<>();
this.maps = new ArrayList<>();
this.tilesets = new ArrayList<>();
this.emitters = new ArrayList<>();
this.blueprints = new ArrayList<>();
}
public static GameFile load(final String file) {
try {
GameFile gameFile = getGameFileFromFile(file);
if (gameFile == null) {
return null;
}
gameFile.getMaps().parallelStream().forEach(map -> {
map.updateTileTerrain();
for (final Tileset tileset : map.getRawTileSets()) {
tileset.load(gameFile.getTilesets());
}
});
return gameFile;
} catch (final JAXBException | IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
@XmlTransient
public List<Map> getMaps() {
return this.maps;
}
@XmlTransient
public List<SpriteSheetInfo> getSpriteSheets() {
return this.spriteSheets;
}
@XmlTransient
public List<Tileset> getTilesets() {
return this.tilesets;
}
@XmlTransient
public List<EmitterData> getEmitters() {
return this.emitters;
}
@XmlTransient
public List<Blueprint> getBluePrints() {
return this.blueprints;
}
public String save(final String fileName, final boolean compress) {
String fileNameWithExtension = fileName;
if (!fileNameWithExtension.endsWith("." + FILE_EXTENSION)) {
fileNameWithExtension += "." + FILE_EXTENSION;
}
final File newFile = new File(fileNameWithExtension);
if (newFile.exists()) {
try {
Files.delete(newFile.toPath().toAbsolutePath());
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
Collections.sort(this.getMaps());
try (FileOutputStream fileOut = new FileOutputStream(newFile, false)) {
final JAXBContext jaxbContext = XmlUtilities.getContext(GameFile.class);
final Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
if (compress) {
final GZIPOutputStream stream = new GZIPOutputStream(fileOut);
jaxbMarshaller.marshal(this, stream);
stream.flush();
stream.close();
} else {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
// first: marshal to byte array
jaxbMarshaller.marshal(this, out);
out.flush();
// second: postprocess xml and then write it to the file
XmlUtilities.saveWithCustomIndetation(new ByteArrayInputStream(out.toByteArray()), fileOut, 1);
out.close();
}
} catch (final JAXBException | IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return newFile.toString();
}
private static GameFile getGameFileFromFile(String file) throws JAXBException, IOException {
final JAXBContext jaxbContext = XmlUtilities.getContext(GameFile.class);
final Unmarshaller um = jaxbContext.createUnmarshaller();
try (InputStream inputStream = FileUtilities.getGameResource(file)) {
// try to get compressed game file
final GZIPInputStream zipStream = new GZIPInputStream(inputStream);
return (GameFile) um.unmarshal(zipStream);
} catch (final ZipException e) {
// if it fails to load the compressed file, get it from plain XML
return XmlUtilities.readFromFile(GameFile.class, file);
}
}
void beforeMarshal(Marshaller m) {
List<SpriteSheetInfo> distinctList = new ArrayList<>();
for (SpriteSheetInfo sprite : this.getSpriteSheets()) {
if (distinctList.stream().anyMatch(x -> x.getName().equals(sprite.getName()) && x.getImage().equals(sprite.getImage()))) {
continue;
}
distinctList.add(sprite);
}
this.spriteSheets = distinctList;
List<Tileset> distinctTilesets = new ArrayList<>();
for (Tileset tileset : this.getTilesets()) {
if (distinctTilesets.stream().anyMatch(x -> x.getName().equals(tileset.getName()))) {
continue;
}
distinctTilesets.add(tileset);
}
this.tilesets = distinctTilesets;
if (this.version == 0) {
this.version = CURRENT_VERSION;
}
}
}
|
package de.jungblut.ner;
import java.util.Collections;
import com.google.common.base.Preconditions;
import de.jungblut.math.DoubleMatrix;
import de.jungblut.math.DoubleVector;
import de.jungblut.math.ViterbiUtils;
import de.jungblut.math.dense.DenseDoubleMatrix;
import de.jungblut.math.dense.DenseDoubleVector;
import de.jungblut.math.minimize.DenseMatrixFolder;
import de.jungblut.math.minimize.Minimizer;
import de.jungblut.math.sparse.SparseDoubleRowMatrix;
/**
* Maximum entropy markov model for named entity recognition (classifying labels
* in sequence learning).
*
* @author thomas.jungblut
*
*/
public final class MaxEntMarkovModel {
private final Minimizer minimizer;
private final boolean verbose;
private final int numIterations;
private DenseDoubleMatrix theta;
private int classes;
public MaxEntMarkovModel(Minimizer minimizer, int numIterations,
boolean verbose) {
this.minimizer = minimizer;
this.numIterations = numIterations;
this.verbose = verbose;
}
public void train(DoubleVector[] features, DenseDoubleVector[] outcome) {
Preconditions
.checkArgument(
features.length == outcome.length && features.length > 0,
"There wasn't at least a single featurevector, or the two array didn't match in size.");
this.classes = outcome[0].getDimension() == 1 ? 2 : outcome[0]
.getDimension();
DoubleMatrix mat = null;
if (features[0].isSparse()) {
mat = new SparseDoubleRowMatrix(features);
} else {
mat = new DenseDoubleMatrix(features);
}
ConditionalLikelihoodCostFunction func = new ConditionalLikelihoodCostFunction(
mat, new DenseDoubleMatrix(outcome));
DenseDoubleVector vx = new DenseDoubleVector(mat.getColumnCount() * classes);
DoubleVector input = minimizer.minimize(func, vx, numIterations, verbose);
theta = DenseMatrixFolder.unfoldMatrix(input, classes,
(int) (input.getLength() / (double) classes));
}
public DoubleVector predict(DoubleVector feature,
DoubleVector[] featuresPerState) {
return ViterbiUtils.decode(theta,
new SparseDoubleRowMatrix(Collections.singletonList(feature)),
new SparseDoubleRowMatrix(featuresPerState), classes).getRowVector(0);
}
// matrix prediction
public DoubleMatrix predict(DoubleMatrix features,
DoubleMatrix featuresPerState) {
return ViterbiUtils.decode(theta, features, featuresPerState, classes);
}
}
|
package gov.nara.nwts.ftapp.importer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
/**
* Abstract class handling the import of a character-delimited text file allowing for individual values to be wrapped by quotation marks.
* @author TBrady
*
*/
public class DelimitedFileReader {
BufferedReader br;
String sep;
String pline;
public DelimitedFileReader(File f, String sep) throws FileNotFoundException, UnsupportedEncodingException {
br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
this.sep = sep;
}
public DelimitedFileReader(InputStream is, String sep) throws FileNotFoundException, UnsupportedEncodingException {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
this.sep = sep;
}
public Vector<String> getRow() throws IOException {
pline = br.readLine();
if (pline == null) {
br.close();
return null;
}
if (!sep.trim().equals("")) pline = pline.trim();
Vector<String> cols = new Vector<String>();
while(pline!=null){
if (!sep.trim().equals("")) pline = pline.trim();
String tpline = getNextString(pline);
cols.add(normalize(tpline));
if (pline.length() == tpline.length()) break;
pline = pline.substring(tpline.length()+sep.length());
}
return cols;
}
protected String getNextString(String in) throws IOException {
return getNextString(in,0);
}
protected String getNextString(String in, int start) throws IOException {
int pos = -1;
if (in.startsWith("\"")) {
int qpos = in.indexOf("\"", (start==0) ? 1 : start);
int qqpos = in.indexOf("\"\"", (start==0) ? 1 : start);
if ((qpos==qqpos)&&(qqpos >= 0)) {
return getNextString(in,qqpos+2);
}
if (qpos == in.length()) {
return in;
}
if (qpos == -1) {
String s = br.readLine();
if (s == null) return pline;
pline += s;
return getNextString(pline, start);
}
pos = in.indexOf(sep,qpos+1);
} else {
pos = in.indexOf(sep, 0);
}
if (pos == -1) return in;
return in.substring(0,pos);
}
public static Vector<Vector<String>> parseFile(File f, String sep) throws IOException{
return parseFile(f,sep,false);
}
public static Vector<Vector<String>> parseFile(File f, String sep, boolean skipFirstLine) throws IOException{
DelimitedFileReader dfr = new DelimitedFileReader(f, sep);
Vector<Vector<String>> rows = new Vector<Vector<String>>();
Vector<String> hrow = new Vector<String>();
if (skipFirstLine) hrow = dfr.getRow();
if (hrow != null) {
for(Vector<String> row = dfr.getRow(); row!=null; row = dfr.getRow()){
rows.add(row);
}
}
return rows;
}
public static Vector<Vector<String>> parseStream(InputStream is, String sep, boolean skipFirstLine) throws IOException{
DelimitedFileReader dfr = new DelimitedFileReader(is, sep);
Vector<Vector<String>> rows = new Vector<Vector<String>>();
Vector<String> hrow = new Vector<String>();
if (skipFirstLine) hrow = dfr.getRow();
if (hrow != null) {
for(Vector<String> row = dfr.getRow(); row!=null; row = dfr.getRow()){
rows.add(row);
}
}
return rows;
}
protected static String normalize(String val) {
val = val.trim();
if (val.startsWith("\"")) {
val = val.substring(1);
} else if (val.startsWith("'")) {
val = val.substring(1);
}
if (val.endsWith("\"")) {
val = val.substring(0,val.length()-1);
} else if (val.endsWith("'")) {
val = val.substring(0,val.length()-1);
}
val = val.replaceAll("\"\"", "\"");
return val;
}
}
|
package org.kuali.kra.award.printing.xmlstream;
import org.apache.xmlbeans.XmlObject;
import org.kuali.coeus.common.framework.custom.attr.CustomAttribute;
import org.kuali.coeus.common.framework.version.history.VersionHistoryService;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.award.awardhierarchy.AwardHierarchy;
import org.kuali.kra.award.awardhierarchy.AwardHierarchyService;
import org.kuali.kra.award.budget.document.AwardBudgetDocument;
import org.kuali.kra.award.customdata.AwardCustomData;
import org.kuali.kra.award.home.Award;
import org.kuali.kra.award.home.AwardAmountInfo;
import org.kuali.kra.award.home.AwardTransferringSponsor;
import org.kuali.kra.award.paymentreports.paymentschedule.AwardPaymentSchedule;
import org.kuali.kra.award.printing.AwardPrintType;
import org.kuali.kra.award.specialreview.AwardSpecialReview;
import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetLineItem;
import org.kuali.kra.printing.schema.*;
import org.kuali.kra.printing.schema.AwardNoticeDocument.AwardNotice.PrintRequirement;
import org.kuali.kra.printing.schema.AwardType.*;
import org.kuali.kra.printing.schema.AwardType.AwardBudgetDetails.BudgetDetails;
import org.kuali.kra.printing.schema.AwardType.AwardOtherDatas.OtherData;
import org.kuali.kra.printing.schema.AwardType.AwardPaymentSchedules.PaymentSchedule;
import org.kuali.kra.printing.schema.AwardType.AwardTransferringSponsors.TransferringSponsor;
import java.util.*;
/**
* This class generates XML that conforms with the XSD related to Award Notice
* Report. The data for XML is derived from {@link org.kuali.coeus.sys.framework.model.KcTransactionalDocumentBase} and
* {@link Map} of details passed to the class.
*
*
*/
public class AwardNoticeXmlStream extends AwardBaseStream {
private static final String REPORTING = "reporting";
private static final String TECHNICAL_REPORTING = "technicalReporting";
private static final String TERMS = "terms";
private static final String SPECIAL_REVIEW = "specialReview";
private static final String SUBCONTRACT = "subcontract";
private static final String SCIENCE_CODE = "keywords";
private static final String PROPOSAL_DUE = "proposalDue";
private static final String PAYMENT = "payment";
private static final String INDIRECT_COST = "fACost";
private static final String FUNDING_SUMMARY="fundingSummary";
private static final String HIERARCHY_INFO = "hierarchyInfo";
private static final String FOREIGN_TRAVEL = "foreignTravel";
private static final String FLOW_THRU = "flowThru";
private static final String EQUIPMENT = "equipment";
private static final String COST_SHARING = "costSharing";
private static final String COMMENTS = "comments";
private static final String CLOSEOUT = "closeout";
private static final String ADDRESS_LIST = "addressList";
private VersionHistoryService versionHistoryService;
/**
* This method generates XML for Award Notice Report. It uses data passed in
* {@link org.kuali.coeus.sys.framework.model.KcTransactionalDocumentBase} for populating the XML nodes. The XML once
* generated is returned as {@link XmlObject}
*
* @param printableBusinessObject
* using which XML is generated
* @param reportParameters
* parameters related to XML generation
* @return {@link XmlObject} representing the XML
*/
public Map<String, XmlObject> generateXmlStream(
KcPersistableBusinessObjectBase printableBusinessObject, Map<String, Object> reportParameters) {
Map<String, XmlObject> xmlObjectList = new LinkedHashMap<String, XmlObject>();
AwardNoticeDocument awardNoticeDocument = AwardNoticeDocument.Factory
.newInstance();
initialize((Award) printableBusinessObject);
if (award != null) {
awardNoticeDocument.setAwardNotice(getAwardNotice(reportParameters));
}
xmlObjectList.put(AwardPrintType.AWARD_NOTICE_REPORT
.getAwardPrintType(), awardNoticeDocument);
return xmlObjectList;
}
/*
* This method initializes the awardDocument ,award and awardAamountInfo
* reference variables
*/
private void initialize(Award award) {
this.awardDocument = award.getAwardDocument();
this.award = award;
List<AwardAmountInfo> awardAmountInfos = award.getAwardAmountInfos();
if (awardAmountInfos != null && !awardAmountInfos.isEmpty()) {
awardAmountInfo = awardAmountInfos.get(awardAmountInfos.size() - 1);
}
}
/*
* This method will set the values to award attributes and finally returns
* award Xml object
*/
protected AwardType getAward() {
AwardType awardType = super.getAward();
awardType.setAwardTransferringSponsors(getAwardTransferringSponsors());
awardType.setAwardPaymentSchedules(getAwardPaymentSchedules());
awardType.setAwardSpecialReviews(getAwardSpecialReviews());
awardType.setAwardOtherDatas(getAwardOtherDatas());
awardType.setAwardBudgetDetails(getAwardBudgetDetails());
awardType.setAwardFundingSummary(getAwardFundingSummary());
awardType.setChildAwardDetails(getChildAwardDetails());
return awardType;
}
/*
* This method will set the values to AwardSpecialReviews attributes and
* finally returns AwardSpecialReviews Xml object
*/
private AwardSpecialReviews getAwardSpecialReviews() {
AwardSpecialReviews awardSpecialReviews = AwardSpecialReviews.Factory
.newInstance();
List<SpecialReviewType> specialReviewTypesList = new LinkedList<SpecialReviewType>();
List<AwardSpecialReview> specialReviewList = award.getSpecialReviews();
SpecialReviewType specialReviewType = null;
for (AwardSpecialReview awardSpecialReview : specialReviewList) {
specialReviewType = getAwardSpecialReview(awardSpecialReview);
specialReviewTypesList.add(specialReviewType);
}
awardSpecialReviews.setSpecialReviewArray(specialReviewTypesList
.toArray(new SpecialReviewType[0]));
return awardSpecialReviews;
}
/*
* This method will set the values to AwardTransferringSponsors attributes
* and finally returns AwardTransferringSponsors Xml object
*/
private AwardTransferringSponsors getAwardTransferringSponsors() {
AwardTransferringSponsors transferringSponsors = AwardTransferringSponsors.Factory
.newInstance();
List<TransferringSponsor> transferringSponsorList = new LinkedList<TransferringSponsor>();
List<AwardTransferringSponsor> awardTransferringSponsorList = award.getAwardTransferringSponsors();
TransferringSponsor transferringSponsor = null;
for (AwardTransferringSponsor awardTransferringSponsor : awardTransferringSponsorList) {
transferringSponsor = getAwardTransferringSponsor(awardTransferringSponsor);
transferringSponsorList.add(transferringSponsor);
}
transferringSponsors
.setTransferringSponsorArray(transferringSponsorList
.toArray(new TransferringSponsor[0]));
return transferringSponsors;
}
/*
* This method will set the values to AwardPaymentSchedules attributes and
* finally returns AwardPaymentSchedules Xml object
*/
private AwardPaymentSchedules getAwardPaymentSchedules() {
AwardPaymentSchedules awardPaymentSchedules = AwardPaymentSchedules.Factory.newInstance();
PaymentSchedule paymentSchedule = null;
List<PaymentSchedule> paymentSchedulesList = new LinkedList<PaymentSchedule>();
for (AwardPaymentSchedule awardPaymentSchedule : award.getPaymentScheduleItems()) {
paymentSchedule = getAwardPaymentSchedule(awardPaymentSchedule);
paymentSchedulesList.add(paymentSchedule);
}
awardPaymentSchedules.setPaymentScheduleArray(paymentSchedulesList
.toArray(new PaymentSchedule[0]));
return awardPaymentSchedules;
}
/*
* This method will set the values to AwardOtherDatas attributes and finally
* returns AwardOtherDatas Xml object
*/
private AwardOtherDatas getAwardOtherDatas() {
AwardOtherDatas awardOtherDatas = AwardOtherDatas.Factory.newInstance();
List<AwardCustomData> awardCustomDataList = award.getAwardCustomDataList();
OtherData otherData = null;
String prevGroupName = null;
OtherGroupType otherGroupType = null;
for (AwardCustomData awardCustomData : awardCustomDataList) {
awardCustomData.refreshReferenceObject("customAttribute");
CustomAttribute customAttribute = awardCustomData.getCustomAttribute();
if (customAttribute != null) {
otherData = awardOtherDatas.addNewOtherData();
String groupName = customAttribute.getGroupName();
String attributeLabel = customAttribute.getLabel();
String attributeValue = awardCustomData.getValue();
if(attributeValue!=null){
if(groupName!=null && !groupName.equals(prevGroupName)){
otherGroupType = otherData.addNewOtherDetails();
otherGroupType.setDescription(groupName);
}
prevGroupName = groupName;
if(otherGroupType!=null){
OtherGroupDetailsType otherGroupDetailsType = otherGroupType.addNewOtherGroupDetails();
otherGroupDetailsType.setColumnName(attributeLabel);
otherGroupDetailsType.setColumnValue(attributeValue);
}
}
}
}
return awardOtherDatas;
}
/*
* This method will set the values to AwardFundingSummary attributes and
* finally returns AwardFundingSummary Xml object
*/
private AwardFundingSummary getAwardFundingSummary() {
AwardFundingSummary awardFundingSummary = AwardFundingSummary.Factory.newInstance();
awardFundingSummary.setFundingSummaryArray(getAwardAmountInfo().getAmountInfoArray());
return awardFundingSummary;
}
/*
* This method will set the values to AwardBudgetDetails attributes and
* finally returns AwardBudgetDetails Xml object
*/
private AwardBudgetDetails getAwardBudgetDetails() {
AwardBudgetDetails awardBudgetDetails = AwardBudgetDetails.Factory.newInstance();
List<BudgetDetails> budgetDetailsList = new ArrayList<BudgetDetails>();
AwardBudgetDocument awardBudgetDocument = getBudgetDocument();
if (awardBudgetDocument != null) {
for (BudgetLineItem budgetLineItem : awardBudgetDocument.getBudget().getBudgetPeriod(0).getBudgetLineItems()) {
BudgetDetails budgetDetails = BudgetDetails.Factory.newInstance();
budgetDetails.setAwardNumber(award.getAwardNumber());
budgetDetails.setSequenceNumber(award.getSequenceNumber());
budgetDetails.setLineItemNumber(budgetLineItem.getLineItemNumber());
budgetDetails.setCostElementCode(budgetLineItem.getCostElement());
budgetDetails.setCostElementDescription(budgetLineItem.getCostElementBO().getDescription());
budgetDetails.setLineItemDescription(budgetLineItem.getLineItemDescription());
budgetDetailsList.add(budgetDetails);
}
}
awardBudgetDetails.setBudgetDetailsArray(budgetDetailsList.toArray(new BudgetDetails[0]));
return awardBudgetDetails;
}
/*
* This method will set the values to ChildAwardDetails attributes and
* finally returns ChildAwardDetails Xml object
*/
private ChildAwardDetails getChildAwardDetails() {
ChildAwardDetails childAwardDetails = ChildAwardDetails.Factory.newInstance();
AwardHierarchy awardHierarchy = getAwardHierarchyService().loadAwardHierarchyBranch(award.getAwardNumber());
List<AwardHierarchy> children = awardHierarchy.getChildren();
for (AwardHierarchy awardHierarchy2 : children) {
setAwardHierarchy(awardHierarchy2, childAwardDetails);
}
return childAwardDetails;
}
private void setAwardHierarchy(AwardHierarchy awardHierarchy, ChildAwardDetails childAwardDetails) {
if(awardHierarchy!=null) {
ChildAwardType childAwardType = childAwardDetails.addNewChildAward();
AwardHierarchyType hierarchyType = childAwardType.addNewAwardHierarchy();
hierarchyType.setAwardNumber(awardHierarchy.getAwardNumber());
hierarchyType.setParentAwardNumber(awardHierarchy.getParentAwardNumber());
hierarchyType.setRootAwardNumber(awardHierarchy.getRootAwardNumber());
setAwardAmountInfoDetails(awardHierarchy,childAwardType);
List<AwardHierarchy> children = awardHierarchy.getChildren();
for (AwardHierarchy awardHierarchy2 : children) {
setAwardHierarchy(awardHierarchy2, childAwardDetails);
}
}
}
private void setAwardAmountInfoDetails(AwardHierarchy awardHierarchy, ChildAwardType childAwardType) {
awardHierarchy.refreshReferenceObject("award");
Award childAward = awardHierarchy.getAward();
AwardAmountInfo awardAmountInfo = childAward.getLastAwardAmountInfo();
if (awardHierarchy.getAward().getAccountNumber() != null) {
childAwardType.setAccountNumber(awardHierarchy.getAward().getAccountNumber());
}
if (awardAmountInfo.getAnticipatedTotalAmount() != null) {
childAwardType.setAnticipatedTotalAmt(awardAmountInfo.getAnticipatedTotalAmount().bigDecimalValue());
}
if (awardAmountInfo.getFinalExpirationDate() != null) {
Calendar finalExpDate = dateTimeService.getCalendar(awardAmountInfo.getFinalExpirationDate());
childAwardType.setFinalExpirationDate(finalExpDate);
}
if (awardAmountInfo.getCurrentFundEffectiveDate() != null) {
Calendar currentFundEffectiveDate = dateTimeService.getCalendar(awardAmountInfo.getCurrentFundEffectiveDate());
childAwardType.setCurrentFundEffectiveDate(currentFundEffectiveDate);
}
if (awardAmountInfo.getAmountObligatedToDate() != null) {
childAwardType.setAmtObligatedToDate(awardAmountInfo.getAmountObligatedToDate().bigDecimalValue());
}
if (awardAmountInfo.getObligationExpirationDate() != null) {
Calendar obligationExpirationDate = dateTimeService.getCalendar(awardAmountInfo.getObligationExpirationDate());
childAwardType.setObligationExpirationDate(obligationExpirationDate);
}
childAwardType.setPIName(childAward.getPrincipalInvestigator().getFullName());
}
private AwardHierarchyService getAwardHierarchyService() {
return KcServiceLocator.getService(AwardHierarchyService.class);
}
/*
* This method sets the values to print requirement attributes and finally
* returns the print requirement xml object
*/
protected PrintRequirement getPrintRequirement(
Map<String, Object> reportParameters) {
PrintRequirement printRequirement = PrintRequirement.Factory
.newInstance();
if (reportParameters != null) {
printRequirement
.setAddressListRequired(getPrintRequirementTypeRequired(
reportParameters, ADDRESS_LIST));
printRequirement
.setCloseoutRequired(getPrintRequirementTypeRequired(
reportParameters, CLOSEOUT));
printRequirement
.setCommentsRequired(getPrintRequirementTypeRequired(
reportParameters, COMMENTS));
printRequirement
.setCostSharingRequired(getPrintRequirementTypeRequired(
reportParameters, COST_SHARING));
printRequirement
.setEquipmentRequired(getPrintRequirementTypeRequired(
reportParameters, EQUIPMENT));
printRequirement
.setFlowThruRequired(getPrintRequirementTypeRequired(
reportParameters, FLOW_THRU));
printRequirement
.setForeignTravelRequired(getPrintRequirementTypeRequired(
reportParameters, FOREIGN_TRAVEL));
printRequirement
.setFundingSummaryRequired(getPrintRequirementTypeRequired(
reportParameters, FUNDING_SUMMARY));
printRequirement
.setHierarchyInfoRequired(getPrintRequirementTypeRequired(
reportParameters, HIERARCHY_INFO));
printRequirement
.setIndirectCostRequired(getPrintRequirementTypeRequired(
reportParameters, INDIRECT_COST));
printRequirement
.setPaymentRequired(getPrintRequirementTypeRequired(
reportParameters, PAYMENT));
printRequirement
.setProposalDueRequired(getPrintRequirementTypeRequired(
reportParameters, PROPOSAL_DUE));
printRequirement
.setSubcontractRequired(getPrintRequirementTypeRequired(
reportParameters, SUBCONTRACT));
printRequirement
.setScienceCodeRequired(getPrintRequirementTypeRequired(
reportParameters, SCIENCE_CODE));
printRequirement
.setSpecialReviewRequired(getPrintRequirementTypeRequired(
reportParameters, SPECIAL_REVIEW));
printRequirement.setTermsRequired(getPrintRequirementTypeRequired(
reportParameters, TERMS));
printRequirement
.setTechnicalReportingRequired(getPrintRequirementTypeRequired(
reportParameters, TECHNICAL_REPORTING));
printRequirement
.setReportingRequired(getPrintRequirementTypeRequired(
reportParameters, REPORTING));
printRequirement.setCurrentDate(dateTimeService
.getCurrentCalendar());
printRequirement.setOtherDataRequired(getPrintRequirementTypeRequired(
reportParameters, OTHER_DATA));
printRequirement
.setSignatureRequired(getPrintRequirementTypeRequired(
reportParameters, SIGNATURE_REQUIRED));
}
return printRequirement;
}
/*
* This method will get the type required if input param checked then it is
* true.If true means value 1 otherwise 0.
*/
private String getPrintRequirementTypeRequired(
Map<String, Object> reportParameters, String printRequirementType) {
String required = null;
if (reportParameters.get(printRequirementType) != null
&& ((Boolean) reportParameters.get(printRequirementType))
.booleanValue()) {
required = REQUIRED;
} else {
required = NOT_REQUIRED;
}
return required;
}
public VersionHistoryService getVersionHistoryService() {
return versionHistoryService;
}
public void setVersionHistoryService(
VersionHistoryService versionHistoryService) {
this.versionHistoryService = versionHistoryService;
}
}
|
package com.archimatetool.editor.diagram.figures;
import org.eclipse.draw2d.Graphics;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import com.archimatetool.editor.Logger;
import com.archimatetool.editor.model.IArchiveManager;
import com.archimatetool.editor.ui.ImageFactory;
import com.archimatetool.model.IIconic;
/**
* Delegate class to handle drawing of iconic types
*
* @author Phillip Beauvoir
*/
@SuppressWarnings("nls")
public class IconicDelegate {
/**
* Setting max image size to this value means that no scaling is done
*/
public static final int MAX_IMAGESIZE = -1;
private IIconic fIconic;
private Image fImage;
private int fMaxImageSize = MAX_IMAGESIZE;
private int topOffset = 0;
private int bottomOffset = 0;
private int leftOffset = 0;
private int rightOffset = 0;
public IconicDelegate(IIconic owner) {
this(owner, MAX_IMAGESIZE);
}
public IconicDelegate(IIconic owner, int maxSize) {
fIconic = owner;
fMaxImageSize = maxSize;
updateImage();
}
/**
* Update the image with a new scaled image
*/
public void updateImage() {
disposeImage();
if(fIconic.getImagePath() != null) {
IArchiveManager archiveManager = (IArchiveManager)fIconic.getAdapter(IArchiveManager.class);
try {
fImage = archiveManager.createImage(fIconic.getImagePath());
}
catch(Exception ex) {
ex.printStackTrace();
Logger.logError("Could not create image!", ex);
}
}
}
public Image getImage() {
return fImage;
}
/**
* Set offset value to use when icon is positioned on the top
* The y position will be moved down by val amount
*/
public void setTopOffset(int val) {
topOffset = val;
}
/**
* Set offset value to use when icon is positioned on the bottom
* The y position will be moved down by val amount (use negative value to move up)
*/
public void setBottomOffset(int val) {
bottomOffset = val;
}
/**
* Set offset value to use when icon is positioned on the left
* The x position will be moved to the right by val amount
*/
public void setLeftOffset(int val) {
leftOffset = val;
}
/**
* Set offset value to use when icon is positioned on the right
* The x position will be moved to the right by val amount (use negative value to move left)
*/
public void setRightOffset(int val) {
rightOffset = val;
}
/**
* Set offset values to use
*/
public void setOffsets(int top, int right, int bottom, int left) {
topOffset = top;
rightOffset = right;
bottomOffset = bottom;
leftOffset = left;
}
/**
* Draw the icon
*/
public void drawIcon(Graphics graphics, org.eclipse.draw2d.geometry.Rectangle bounds) {
if(fImage != null) {
Rectangle imageBounds = fImage.getBounds();
// New Image size, possibly scaled
Rectangle newSize = getImageSize(imageBounds);
int width = newSize.width;
int height = newSize.height;
int x = bounds.x;
int y = bounds.y;
switch(fIconic.getImagePosition()) {
case IIconic.ICON_POSITION_TOP_LEFT:
x += leftOffset;
y += topOffset;
break;
case IIconic.ICON_POSITION_TOP_CENTRE:
x = bounds.x + ((bounds.width - width) / 2);
y += topOffset;
break;
case IIconic.ICON_POSITION_TOP_RIGHT:
x = (bounds.x + bounds.width) - width + rightOffset;
y += topOffset;
break;
case IIconic.ICON_POSITION_MIDDLE_LEFT:
x += leftOffset;
y = bounds.y + ((bounds.height - height) / 2);
break;
case IIconic.ICON_POSITION_MIDDLE_CENTRE:
x = bounds.x + ((bounds.width - width) / 2);
y = bounds.y + ((bounds.height - height) / 2);
break;
case IIconic.ICON_POSITION_MIDDLE_RIGHT:
x = (bounds.x + bounds.width) - width + rightOffset;
y = bounds.y + ((bounds.height - height) / 2);
break;
case IIconic.ICON_POSITION_BOTTOM_LEFT:
x += leftOffset;
y = (bounds.y + bounds.height) - height + bottomOffset;
break;
case IIconic.ICON_POSITION_BOTTOM_CENTRE:
x = bounds.x + ((bounds.width - width) / 2);
y = (bounds.y + bounds.height) - height + bottomOffset;
break;
case IIconic.ICON_POSITION_BOTTOM_RIGHT:
x = (bounds.x + bounds.width) - width + rightOffset;
y = (bounds.y + bounds.height) - height + bottomOffset;
break;
default:
break;
}
graphics.pushState();
graphics.setAntialias(SWT.ON);
graphics.setInterpolation(SWT.HIGH);
graphics.setClip(bounds); // At zoom levels > 100 the image can be painted beyond the bounds
// Ensure image is drawn in full alpha
graphics.setAlpha(255);
// Original size
if(fMaxImageSize == MAX_IMAGESIZE) {
graphics.drawImage(fImage, x, y);
}
// Scaled size
else {
graphics.drawImage(fImage, 0, 0, imageBounds.width, imageBounds.height, x, y, width, height);
}
graphics.popState();
}
}
/**
* @return the possibly scaled image size or original image size if not scaled
*/
private Rectangle getImageSize(Rectangle imageBounds) {
// Use image bounds
if(fMaxImageSize == MAX_IMAGESIZE) {
return imageBounds;
}
return ImageFactory.getScaledImageSize(fImage, fMaxImageSize);
}
public void dispose() {
disposeImage();
fIconic = null;
}
private void disposeImage() {
if(fImage != null && !fImage.isDisposed()) {
fImage.dispose();
fImage = null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.