code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.runtime.authentication.standard;
import java.util.List;
import org.apache.isis.core.commons.components.InstallerAbstract;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.runtime.authentication.AuthenticationManager;
import org.apache.isis.core.runtime.authentication.AuthenticationManagerInstaller;
public abstract class AuthenticationManagerStandardInstallerAbstract extends InstallerAbstract implements AuthenticationManagerInstaller {
public AuthenticationManagerStandardInstallerAbstract(
final String name,
final IsisConfiguration isisConfiguration) {
super(name, isisConfiguration);
}
@Override
public final AuthenticationManager createAuthenticationManager() {
final AuthenticationManagerStandard authenticationManager = createAuthenticationManagerStandard();
for (final Authenticator authenticator : createAuthenticators()) {
authenticationManager.addAuthenticator(authenticator);
}
return authenticationManager;
}
protected AuthenticationManagerStandard createAuthenticationManagerStandard() {
return new AuthenticationManagerStandard(getConfiguration());
}
/**
* Hook method
*
* @return
*/
protected abstract List<Authenticator> createAuthenticators();
@Override
public List<Class<?>> getTypes() {
return listOf(AuthenticationManager.class);
}
}
| niv0/isis | core/metamodel/src/main/java/org/apache/isis/core/runtime/authentication/standard/AuthenticationManagerStandardInstallerAbstract.java | Java | apache-2.0 | 2,324 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.volume;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
public class IconPulser {
private static final float PULSE_SCALE = 1.1f;
private final Interpolator mFastOutSlowInInterpolator;
public IconPulser(Context context) {
mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
android.R.interpolator.fast_out_slow_in);
}
public void start(final View target) {
if (target == null || target.getScaleX() != 1) return; // n/a, or already running
target.animate().cancel();
target.animate().scaleX(PULSE_SCALE).scaleY(PULSE_SCALE)
.setInterpolator(mFastOutSlowInInterpolator)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
target.animate().scaleX(1).scaleY(1).setListener(null);
}
});
}
}
| Ant-Droid/android_frameworks_base_OLD | packages/SystemUI/src/com/android/systemui/volume/IconPulser.java | Java | apache-2.0 | 1,800 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.clients;
/**
* A callback interface for attaching an action to be executed when a request is complete and the corresponding response
* has been received. This handler will also be invoked if there is a disconnection while handling the request.
*/
public interface RequestCompletionHandler {
void onComplete(ClientResponse response);
}
| guozhangwang/kafka | clients/src/main/java/org/apache/kafka/clients/RequestCompletionHandler.java | Java | apache-2.0 | 1,168 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal.parse;
import antlr.*;
import org.apache.geode.cache.query.internal.QCompiler;
public class ASTTypeCast extends GemFireAST {
private static final long serialVersionUID = -6368577668325776355L;
public ASTTypeCast() {}
public ASTTypeCast(Token t) {
super(t);
}
@Override
public void compile(QCompiler compiler) {
super.compile(compiler);
// there's a type on the stack now
compiler.typecast();
}
}
| pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/cache/query/internal/parse/ASTTypeCast.java | Java | apache-2.0 | 1,274 |
/*
* Copyright (c) 2013 Michael Berlin, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.test.osd.rwre;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.xtreemfs.osd.storage.HashStorageLayout;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestHelper;
public class FixWrongMasterEpochDirectoryTest {
@Rule
public final TestRule testLog = TestHelper.testLog;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void testAutomaticMoveToCorrectDirectory() throws IOException {
final String globalFileId = "f32b0854-91eb-44d8-adf8-65bb8baf5f60:13193";
final String correctedFileId = globalFileId;
final String brokenFileId = "/" + correctedFileId;
final HashStorageLayout hsl = new HashStorageLayout(SetupUtils.createOSD1Config(), new MetadataCache());
// Cleanup previous runs.
hsl.deleteFile(brokenFileId, true);
hsl.deleteFile(correctedFileId, true);
final File brokenFileDir = new File(hsl.generateAbsoluteFilePath(brokenFileId));
final File correctedFileDir = new File(hsl.generateAbsoluteFilePath(correctedFileId));
// Set masterepoch using the wrong id.
assertFalse(brokenFileDir.isDirectory());
assertFalse(correctedFileDir.isDirectory());
hsl.setMasterEpoch(brokenFileId, 1);
assertTrue(brokenFileDir.isDirectory());
// Get the masterepoch with the correct id.
assertEquals(1, hsl.getMasterEpoch(correctedFileId));
assertFalse(brokenFileDir.isDirectory());
assertTrue(correctedFileDir.isDirectory());
// Get the masterepoch of a file which does not exist.
assertEquals(0, hsl.getMasterEpoch("fileIdDoesNotExist"));
}
}
| jswrenn/xtreemfs | java/servers/test/org/xtreemfs/test/osd/rwre/FixWrongMasterEpochDirectoryTest.java | Java | bsd-3-clause | 2,315 |
package ibxm;
/* A data array dynamically loaded from an InputStream. */
public class Data {
private int bufLen;
private byte[] buffer;
private java.io.InputStream stream;
public Data( java.io.InputStream inputStream ) throws java.io.IOException {
bufLen = 1 << 16;
buffer = new byte[ bufLen ];
stream = inputStream;
readFully( stream, buffer, 0, bufLen );
}
public Data( byte[] data ) {
bufLen = data.length;
buffer = data;
}
public byte sByte( int offset ) throws java.io.IOException {
load( offset, 1 );
return buffer[ offset ];
}
public int uByte( int offset ) throws java.io.IOException {
load( offset, 1 );
return buffer[ offset ] & 0xFF;
}
public int ubeShort( int offset ) throws java.io.IOException {
load( offset, 2 );
return ( ( buffer[ offset ] & 0xFF ) << 8 ) | ( buffer[ offset + 1 ] & 0xFF );
}
public int uleShort( int offset ) throws java.io.IOException {
load( offset, 2 );
return ( buffer[ offset ] & 0xFF ) | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 );
}
public int uleInt( int offset ) throws java.io.IOException {
load( offset, 4 );
int value = buffer[ offset ] & 0xFF;
value = value | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 );
value = value | ( ( buffer[ offset + 2 ] & 0xFF ) << 16 );
value = value | ( ( buffer[ offset + 3 ] & 0x7F ) << 24 );
return value;
}
public String strLatin1( int offset, int length ) throws java.io.IOException {
load( offset, length );
char[] str = new char[ length ];
for( int idx = 0; idx < length; idx++ ) {
int chr = buffer[ offset + idx ] & 0xFF;
str[ idx ] = chr < 32 ? 32 : ( char ) chr;
}
return new String( str );
}
public String strCp850( int offset, int length ) throws java.io.IOException {
load( offset, length );
try {
char[] str = new String( buffer, offset, length, "Cp850" ).toCharArray();
for( int idx = 0; idx < str.length; idx++ ) {
str[ idx ] = str[ idx ] < 32 ? 32 : str[ idx ];
}
return new String( str );
} catch( java.io.UnsupportedEncodingException e ) {
return strLatin1( offset, length );
}
}
public short[] samS8( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
for( int idx = 0; idx < length; idx++ ) {
sampleData[ idx ] = ( short ) ( buffer[ offset + idx ] << 8 );
}
return sampleData;
}
public short[] samS8D( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
int sam = 0;
for( int idx = 0; idx < length; idx++ ) {
sam += buffer[ offset + idx ];
sampleData[ idx ] = ( short ) ( sam << 8 );
}
return sampleData;
}
public short[] samU8( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
for( int idx = 0; idx < length; idx++ ) {
sampleData[ idx ] = ( short ) ( ( ( buffer[ offset + idx ] & 0xFF ) - 128 ) << 8 );
}
return sampleData;
}
public short[] samS16( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
for( int idx = 0; idx < samples; idx++ ) {
sampleData[ idx ] = ( short ) ( ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 ) );
}
return sampleData;
}
public short[] samS16D( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
int sam = 0;
for( int idx = 0; idx < samples; idx++ ) {
sam += ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 );
sampleData[ idx ] = ( short ) sam;
}
return sampleData;
}
public short[] samU16( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
for( int idx = 0; idx < samples; idx++ ) {
int sam = ( buffer[ offset + idx * 2 ] & 0xFF ) | ( ( buffer[ offset + idx * 2 + 1 ] & 0xFF ) << 8 );
sampleData[ idx ] = ( short ) ( sam - 32768 );
}
return sampleData;
}
private void load( int offset, int length ) throws java.io.IOException {
while( offset + length > bufLen ) {
int newBufLen = bufLen << 1;
byte[] newBuf = new byte[ newBufLen ];
System.arraycopy( buffer, 0, newBuf, 0, bufLen );
if( stream != null ) {
readFully( stream, newBuf, bufLen, newBufLen - bufLen );
}
bufLen = newBufLen;
buffer = newBuf;
}
}
private static void readFully( java.io.InputStream inputStream, byte[] buffer, int offset, int length ) throws java.io.IOException {
int read = 1, end = offset + length;
while( read > 0 ) {
read = inputStream.read( buffer, offset, end - offset );
offset += read;
}
}
}
| Arcnor/micromod | ibxm/src/main/java/ibxm/Data.java | Java | bsd-3-clause | 4,767 |
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
public class Bow implements Weapon {
@Override
public String toString() {
return "Bow";
}
}
| Crossy147/java-design-patterns | factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java | Java | mit | 1,281 |
package org.knowm.xchange.ripple;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import org.junit.Test;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.ripple.dto.account.ITransferFeeSource;
import org.knowm.xchange.ripple.dto.account.RippleAccountBalances;
import org.knowm.xchange.ripple.dto.account.RippleAccountSettings;
import org.knowm.xchange.ripple.dto.marketdata.RippleOrderBook;
import org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction;
import org.knowm.xchange.ripple.dto.trade.RippleAccountOrders;
import org.knowm.xchange.ripple.dto.trade.RippleLimitOrder;
import org.knowm.xchange.ripple.dto.trade.RippleOrderTransaction;
import org.knowm.xchange.ripple.dto.trade.RipplePaymentTransaction;
import org.knowm.xchange.ripple.dto.trade.RippleUserTrade;
import org.knowm.xchange.ripple.service.params.RippleMarketDataParams;
import org.knowm.xchange.ripple.service.params.RippleTradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
public class RippleAdaptersTest implements ITransferFeeSource {
@Test
public void adaptAccountInfoTest() throws IOException {
// Read in the JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/account/example-account-balances.json");
// Use Jackson to parse it
final ObjectMapper mapper = new ObjectMapper();
final RippleAccountBalances rippleAccount = mapper.readValue(is, RippleAccountBalances.class);
// Convert to xchange object and check field values
final AccountInfo account = RippleAdapters.adaptAccountInfo(rippleAccount, "username");
assertThat(account.getWallets()).hasSize(2);
assertThat(account.getUsername()).isEqualTo("username");
assertThat(account.getTradingFee()).isEqualTo(BigDecimal.ZERO);
final Wallet counterWallet = account.getWallet("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(counterWallet.getId()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(counterWallet.getBalances()).hasSize(2);
final Balance btcBalance = counterWallet.getBalance(Currency.BTC);
assertThat(btcBalance.getTotal()).isEqualTo("0.038777349225374");
assertThat(btcBalance.getCurrency()).isEqualTo(Currency.BTC);
final Balance usdBalance = counterWallet.getBalance(Currency.USD);
assertThat(usdBalance.getTotal()).isEqualTo("10");
assertThat(usdBalance.getCurrency()).isEqualTo(Currency.USD);
final Wallet mainWallet = account.getWallet("main");
assertThat(mainWallet.getBalances()).hasSize(1);
final Balance xrpBalance = mainWallet.getBalance(Currency.XRP);
assertThat(xrpBalance.getTotal()).isEqualTo("861.401578");
assertThat(xrpBalance.getCurrency()).isEqualTo(Currency.XRP);
}
@Test
public void adaptOrderBookTest() throws IOException {
// Read in the JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/marketdata/example-order-book.json");
final CurrencyPair currencyPair = CurrencyPair.XRP_BTC;
// Test data uses Bitstamp issued BTC
final RippleMarketDataParams params = new RippleMarketDataParams();
params.setCounterCounterparty("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
// Use Jackson to parse it
final ObjectMapper mapper = new ObjectMapper();
final RippleOrderBook rippleOrderBook = mapper.readValue(is, RippleOrderBook.class);
// Convert to xchange object and check field values
final OrderBook orderBook =
RippleAdapters.adaptOrderBook(rippleOrderBook, params, currencyPair);
assertThat(orderBook.getBids()).hasSize(10);
assertThat(orderBook.getAsks()).hasSize(10);
final LimitOrder lastBid = orderBook.getBids().get(9);
assertThat(lastBid).isInstanceOf(RippleLimitOrder.class);
assertThat(lastBid.getCurrencyPair()).isEqualTo(currencyPair);
assertThat(((RippleLimitOrder) lastBid).getCounterCounterparty())
.isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(lastBid.getType()).isEqualTo(OrderType.BID);
assertThat(lastBid.getId()).isEqualTo("1303704");
assertThat(lastBid.getOriginalAmount()).isEqualTo("66314.537782");
assertThat(lastBid.getLimitPrice()).isEqualTo("0.00003317721777288062");
final LimitOrder firstAsk = orderBook.getAsks().get(0);
assertThat(firstAsk).isInstanceOf(RippleLimitOrder.class);
assertThat(firstAsk.getCurrencyPair()).isEqualTo(currencyPair);
assertThat(((RippleLimitOrder) firstAsk).getCounterCounterparty())
.isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(firstAsk.getType()).isEqualTo(OrderType.ASK);
assertThat(firstAsk.getId()).isEqualTo("1011310");
assertThat(firstAsk.getOriginalAmount()).isEqualTo("35447.914936");
assertThat(firstAsk.getLimitPrice()).isEqualTo("0.00003380846624897726");
}
@Test
public void adaptOpenOrdersTest() throws JsonParseException, JsonMappingException, IOException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read in the JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream("/org/knowm/xchange/ripple/dto/trade/example-account-orders.json");
final ObjectMapper mapper = new ObjectMapper();
final RippleAccountOrders response = mapper.readValue(is, RippleAccountOrders.class);
// Convert to XChange orders
final OpenOrders orders = RippleAdapters.adaptOpenOrders(response, roundingScale);
assertThat(orders.getOpenOrders()).hasSize(12);
final LimitOrder firstOrder = orders.getOpenOrders().get(0);
assertThat(firstOrder).isInstanceOf(RippleLimitOrder.class);
assertThat(firstOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC);
assertThat(((RippleLimitOrder) firstOrder).getCounterCounterparty())
.isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(firstOrder.getId()).isEqualTo("5");
assertThat(firstOrder.getLimitPrice()).isEqualTo("0.00003226");
assertThat(firstOrder.getTimestamp()).isNull();
assertThat(firstOrder.getOriginalAmount()).isEqualTo("1");
assertThat(firstOrder.getType()).isEqualTo(OrderType.BID);
final LimitOrder secondOrder = orders.getOpenOrders().get(1);
assertThat(secondOrder).isInstanceOf(RippleLimitOrder.class);
assertThat(secondOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC);
assertThat(((RippleLimitOrder) secondOrder).getCounterCounterparty())
.isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
assertThat(secondOrder.getId()).isEqualTo("7");
// Price = 15159.38551342023 / 123.123456
assertThat(secondOrder.getLimitPrice())
.isEqualTo("123.12345677999998635515884154518859509596611713043533");
assertThat(secondOrder.getTimestamp()).isNull();
assertThat(secondOrder.getOriginalAmount()).isEqualTo("123.123456");
assertThat(secondOrder.getType()).isEqualTo(OrderType.ASK);
}
@Override
public BigDecimal getTransferFeeRate(final String address) throws IOException {
final InputStream is =
getClass()
.getResourceAsStream(
String.format(
"/org/knowm/xchange/ripple/dto/account/example-account-settings-%s.json",
address));
final ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(is, RippleAccountSettings.class).getSettings().getTransferFeeRate();
}
@Test
public void adaptTrade_BuyXRP_SellBTC()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json");
final ObjectMapper mapper = new ObjectMapper();
final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class);
final RippleTradeHistoryParams params = new RippleTradeHistoryParams();
params.addPreferredCounterCurrency(Currency.BTC);
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("0000000000000000000000000000000000000000000000000000000000000000");
assertThat(trade.getOrderId()).isEqualTo("1010");
// Price = 0.000029309526038 * 0.998
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("0.000029250906985924")
.setScale(roundingScale, RoundingMode.HALF_UP)
.stripTrailingZeros());
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z"));
assertThat(trade.getOriginalAmount()).isEqualTo("1");
assertThat(trade.getType()).isEqualTo(OrderType.BID);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEmpty();
assertThat(ripple.getBaseTransferFee()).isZero();
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
// Transfer fee = 0.000029309526038 * 0.002
assertThat(ripple.getCounterTransferFee()).isEqualTo("0.000000058619052076");
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
}
@Test
public void adaptTrade_SellBTC_BuyXRP()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json");
final ObjectMapper mapper = new ObjectMapper();
final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class);
final RippleTradeHistoryParams params = new RippleTradeHistoryParams();
params.addPreferredBaseCurrency(Currency.BTC);
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("0000000000000000000000000000000000000000000000000000000000000000");
assertThat(trade.getOrderId()).isEqualTo("1010");
// Price = 1.0 / (0.000029309526038 * 0.998)
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("34186.97411609205306550363511634115030681332485583111528")
.setScale(roundingScale, RoundingMode.HALF_UP));
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z"));
// Quantity = 0.000029309526038 * 0.998
assertThat(trade.getOriginalAmount()).isEqualTo("0.000029250906985924");
assertThat(trade.getType()).isEqualTo(OrderType.ASK);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
// Transfer fee = 0.000029309526038 * 0.002
assertThat(ripple.getBaseTransferFee()).isEqualTo("0.000000058619052076");
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEmpty();
assertThat(ripple.getCounterTransferFee()).isZero();
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
}
@Test
public void adaptTrade_SellXRP_BuyBTC()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json");
final ObjectMapper mapper = new ObjectMapper();
final IRippleTradeTransaction response = mapper.readValue(is, RippleOrderTransaction.class);
final RippleTradeHistoryParams params = new RippleTradeHistoryParams();
params.setCurrencyPair(CurrencyPair.XRP_BTC);
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("1111111111111111111111111111111111111111111111111111111111111111");
assertThat(trade.getOrderId()).isEqualTo("1111");
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("0.000028572057152")
.setScale(roundingScale, RoundingMode.HALF_UP)
.stripTrailingZeros());
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z"));
assertThat(trade.getOriginalAmount()).isEqualTo("1");
assertThat(trade.getType()).isEqualTo(OrderType.ASK);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEmpty();
assertThat(ripple.getBaseTransferFee()).isZero();
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
assertThat(ripple.getCounterTransferFee()).isZero();
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
// make sure that if the IRippleTradeTransaction is adapted again it returns the same values
final UserTrade trade2 = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade2.getCurrencyPair()).isEqualTo(trade.getCurrencyPair());
assertThat(trade2.getFeeAmount()).isEqualTo(trade.getFeeAmount());
assertThat(trade2.getFeeCurrency()).isEqualTo(trade.getFeeCurrency());
assertThat(trade2.getId()).isEqualTo(trade.getId());
assertThat(trade2.getOrderId()).isEqualTo(trade.getOrderId());
assertThat(trade2.getPrice()).isEqualTo(trade.getPrice());
assertThat(trade2.getTimestamp()).isEqualTo(trade.getTimestamp());
assertThat(trade2.getOriginalAmount()).isEqualTo(trade.getOriginalAmount());
assertThat(trade2.getType()).isEqualTo(trade.getType());
}
@Test
public void adaptTrade_BuyBTC_SellXRP()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json");
final ObjectMapper mapper = new ObjectMapper();
final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class);
final RippleTradeHistoryParams params = new RippleTradeHistoryParams();
params.addPreferredBaseCurrency(Currency.BTC);
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("1111111111111111111111111111111111111111111111111111111111111111");
assertThat(trade.getOrderId()).isEqualTo("1111");
// Price = 1.0 / 0.000028572057152
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("34999.23000574012011552062010939099496310569328655387396")
.setScale(roundingScale, RoundingMode.HALF_UP)
.stripTrailingZeros());
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z"));
assertThat(trade.getOriginalAmount()).isEqualTo("0.000028572057152");
assertThat(trade.getType()).isEqualTo(OrderType.BID);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
assertThat(ripple.getBaseTransferFee()).isZero();
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEmpty();
assertThat(ripple.getCounterTransferFee()).isZero();
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
}
@Test
public void adaptTrade_BuyBTC_SellBTC()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-trade-buyBTC-sellBTC.json");
final ObjectMapper mapper = new ObjectMapper();
final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class);
final TradeHistoryParams params = new TradeHistoryParams() {};
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.BTC);
assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("2222222222222222222222222222222222222222222222222222222222222222");
assertThat(trade.getOrderId()).isEqualTo("2222");
// Price = 0.501 * 0.998 / 0.50150835545121407952
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("0.99698837430165008596385145696065600512973847422746")
.setScale(roundingScale, RoundingMode.HALF_UP));
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2022-22-22T22:22:22.222Z"));
assertThat(trade.getOriginalAmount()).isEqualTo("0.50150835545121407952");
assertThat(trade.getType()).isEqualTo(OrderType.BID);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
assertThat(ripple.getBaseTransferFee()).isZero();
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
// Transfer fee = 0.501 * 0.002
assertThat(ripple.getCounterTransferFee()).isEqualTo("0.001002");
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
}
@Test
public void adaptTrade_PaymentPassthrough()
throws JsonParseException, JsonMappingException, IOException, ParseException {
final RippleExchange exchange = new RippleExchange();
final int roundingScale = exchange.getRoundingScale();
// Read the trade JSON from the example resources
final InputStream is =
getClass()
.getResourceAsStream(
"/org/knowm/xchange/ripple/dto/trade/example-payment-passthrough.json");
final ObjectMapper mapper = new ObjectMapper();
final RipplePaymentTransaction response = mapper.readValue(is, RipplePaymentTransaction.class);
final TradeHistoryParams params = new TradeHistoryParams() {};
final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale);
assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.XRP);
assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC);
assertThat(trade.getFeeAmount()).isEqualTo("0.012");
assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(trade.getId())
.isEqualTo("GHRE072948B95345396B2D9A364363GDE521HRT67QQRGGRTHYTRUP0RRB631107");
assertThat(trade.getOrderId()).isEqualTo("9338");
// Price = 0.009941478580724 / (349.559725 - 0.012)
assertThat(trade.getPrice())
.isEqualTo(
new BigDecimal("0.00002844097635229638527900589254299967193321026478")
.setScale(roundingScale, RoundingMode.HALF_UP));
assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2015-08-07T03:58:10.000Z"));
assertThat(trade.getOriginalAmount()).isEqualTo("349.547725");
assertThat(trade.getType()).isEqualTo(OrderType.ASK);
assertThat(trade).isInstanceOf(RippleUserTrade.class);
final RippleUserTrade ripple = (RippleUserTrade) trade;
assertThat(ripple.getBaseCounterparty()).isEqualTo("");
assertThat(ripple.getBaseTransferFee()).isZero();
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP);
assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base);
assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q");
// Transfer fee = 0.501 * 0.002
assertThat(ripple.getCounterTransferFee()).isEqualTo("0");
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC);
assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter);
}
}
| timmolter/XChange | xchange-ripple/src/test/java/org/knowm/xchange/ripple/RippleAdaptersTest.java | Java | mit | 24,065 |
package com.aspose.cells.model;
public class SideWall {
private Link link = null;
public Link getLink() {
return link;
}
public void setLink(Link link) {
this.link = link;
}
}
| aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/cells/model/SideWall.java | Java | mit | 210 |
package com.punchthrough.bean.sdk.internal.upload.sketch;
public enum SketchUploadState {
INACTIVE, RESETTING_REMOTE, SENDING_START_COMMAND, SENDING_BLOCKS, FINISHED
}
| PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/SketchUploadState.java | Java | mit | 173 |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event.item.inventory;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.item.inventory.ItemStack;
public interface ChangeInventoryEvent extends TargetInventoryEvent, AffectSlotEvent, Cancellable {
/**
* Fired when a {@link Living} changes it's equipment.
*/
interface Equipment extends ChangeInventoryEvent {}
/**
* Fired when a {@link Living} changes it's held {@link ItemStack}.
*/
interface Held extends ChangeInventoryEvent {}
interface Transfer extends ChangeInventoryEvent {}
interface Pickup extends ChangeInventoryEvent {}
}
| kashike/SpongeAPI | src/main/java/org/spongepowered/api/event/item/inventory/ChangeInventoryEvent.java | Java | mit | 1,942 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.framework.context;
import org.eclipse.persistence.tools.workbench.framework.resources.IconResourceFileNameMap;
import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepository;
import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepositoryWrapper;
/**
* Wrap another context and expand its resource
* repository with a resource repository wrapper.
*/
public class ExpandedResourceRepositoryApplicationContext extends ApplicationContextWrapper {
private ResourceRepository expandedResourceRepository;
// ********** constructor/initialization **********
/**
* Construct a context with an expanded resource repository
* that adds the resources in the specified resource bundle and icon map
* to the original resource repository.
*/
public ExpandedResourceRepositoryApplicationContext(ApplicationContext delegate, Class resourceBundleClass, IconResourceFileNameMap iconResourceFileNameMap) {
super(delegate);
this.expandedResourceRepository = new ResourceRepositoryWrapper(this.delegateResourceRepository(), resourceBundleClass, iconResourceFileNameMap);
}
// ********** non-delegated behavior **********
/**
* @see ApplicationContextWrapper#getResourceRepository()
*/
public ResourceRepository getResourceRepository() {
return this.expandedResourceRepository;
}
// ********** additional behavior **********
/**
* Return the original, unwrapped resource repository.
*/
public ResourceRepository delegateResourceRepository() {
return this.getDelegate().getResourceRepository();
}
}
| RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench/framework/source/org/eclipse/persistence/tools/workbench/framework/context/ExpandedResourceRepositoryApplicationContext.java | Java | epl-1.0 | 2,433 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.mappings.transformers;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.core.mappings.transformers.CoreFieldTransformer;
import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
/**
* PUBLIC:
* This interface is used by the Transformation Mapping to build the value for a
* specific field. The user must provide implementations of this interface to the
* Transformation Mapping.
* @author mmacivor
* @since 10.1.3
*/
public interface FieldTransformer extends CoreFieldTransformer<Session> {
/**
* Initialize this transformer. Only required if the user needs some special
* information from the mapping in order to do the transformation
* @param mapping - the mapping this transformer is associated with.
*/
public void initialize(AbstractTransformationMapping mapping);
/**
* @param instance - an instance of the domain class which contains the attribute
* @param session - the current session
* @param fieldName - the name of the field being transformed. Used if the user wants to use this transformer for multiple fields.
* @return - The value to be written for the field associated with this transformer
*/
@Override
public Object buildFieldValue(Object instance, String fieldName, Session session);
}
| RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/mappings/transformers/FieldTransformer.java | Java | epl-1.0 | 2,097 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.writing;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.sessions.server.ClientSession;
import org.eclipse.persistence.testing.framework.WriteObjectTest;
/**
* Test changing private parts of an object.
*/
public class ComplexUpdateTest extends WriteObjectTest {
/** The object which is actually changed */
public Object workingCopy;
public boolean usesUnitOfWork = false;
public boolean usesNestedUnitOfWork = false;
public boolean shouldCommitParent = false;
/** TODO: Set this to true, and fix issues from tests that fail. */
public boolean shouldCompareClone = true;
public ComplexUpdateTest() {
super();
}
public ComplexUpdateTest(Object originalObject) {
super(originalObject);
}
protected void changeObject() {
// By default do nothing
}
public void commitParentUnitOfWork() {
useNestedUnitOfWork();
this.shouldCommitParent = true;
}
public String getName() {
return super.getName() + new Boolean(usesUnitOfWork) + new Boolean(usesNestedUnitOfWork);
}
public void reset() {
if (getExecutor().getSession().isUnitOfWork()) {
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
// Do the same for nested units of work.
if (getExecutor().getSession().isUnitOfWork()) {
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
}
}
super.reset();
}
protected void setup() {
super.setup();
if (this.usesUnitOfWork) {
getExecutor().setSession(getSession().acquireUnitOfWork());
if (this.usesNestedUnitOfWork) {
getExecutor().setSession(getSession().acquireUnitOfWork());
}
this.workingCopy = ((UnitOfWork)getSession()).registerObject(this.objectToBeWritten);
} else {
this.workingCopy = this.objectToBeWritten;
}
}
protected void test() {
changeObject();
if (this.usesUnitOfWork) {
// Ensure that the original has not been changed.
if (!((UnitOfWork)getSession()).getParent().compareObjects(this.originalObject, this.objectToBeWritten)) {
throw new TestErrorException("The original object was changed through changing the clone.");
}
((UnitOfWork)getSession()).commit();
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
if (this.usesNestedUnitOfWork) {
if (this.shouldCommitParent) {
((UnitOfWork)getSession()).commit();
}
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
}
// Ensure that the clone matches the cache.
if (this.shouldCompareClone) {
ClassDescriptor descriptor = getSession().getClassDescriptor(this.objectToBeWritten);
if(descriptor.shouldIsolateObjectsInUnitOfWork()) {
getSession().logMessage("ComplexUpdateTest: descriptor.shouldIsolateObjectsInUnitOfWork() == null. In this case object's changes are not merged back into parent's cache");
} else if (descriptor.shouldIsolateProtectedObjectsInUnitOfWork() && getSession().isClientSession()){
if (!getAbstractSession().compareObjects(this.workingCopy, ((ClientSession)getSession()).getParent().getIdentityMapAccessor().getFromIdentityMap(this.workingCopy))) {
throw new TestErrorException("The clone does not match the cached object.");
}
}
else {
if (!getAbstractSession().compareObjects(this.workingCopy, this.objectToBeWritten)) {
throw new TestErrorException("The clone does not match the cached object.");
}
}
}
} else {
super.test();
}
}
public void useNestedUnitOfWork() {
this.usesNestedUnitOfWork = true;
this.usesUnitOfWork = true;
}
}
| RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/writing/ComplexUpdateTest.java | Java | epl-1.0 | 5,045 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.jpa.advanced;
import org.eclipse.persistence.testing.models.jpa.advanced.Project;
/**
* Tests the @PostUpdate events from an Entity.
*
* @author Guy Pelletier
*/
public class EntityMethodPostUpdateTest extends CallbackEventTest {
public void test() throws Exception {
m_beforeEvent = 0; // Loading a new object to update, count starts at 0.
Project project = updateProject();
m_afterEvent = project.post_update_count;
}
}
| RallySoftware/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/advanced/EntityMethodPostUpdateTest.java | Java | epl-1.0 | 1,234 |
/*
* OCaml Support For IntelliJ Platform.
* Copyright (C) 2010 Maxim Manuylov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package manuylov.maxim.ocaml.lang.parser.psi.element.impl;
import com.intellij.lang.ASTNode;
import manuylov.maxim.ocaml.lang.parser.psi.OCamlElementVisitor;
import manuylov.maxim.ocaml.lang.parser.psi.element.OCamlParenthesesTypeParameters;
import org.jetbrains.annotations.NotNull;
/**
* @author Maxim.Manuylov
* Date: 13.05.2010
*/
public class OCamlParenthesesTypeParametersImpl extends OCamlParenthesesImpl implements OCamlParenthesesTypeParameters {
public OCamlParenthesesTypeParametersImpl(@NotNull final ASTNode node) {
super(node);
}
public void visit(@NotNull final OCamlElementVisitor visitor) {
visitor.visitParenthesesTypeParameters(this);
}
}
| emmeryn/intellij-ocaml | OCamlSources/src/manuylov/maxim/ocaml/lang/parser/psi/element/impl/OCamlParenthesesTypeParametersImpl.java | Java | gpl-2.0 | 1,487 |
/*
* Copyright (C) 2013 University of Dundee & Open Microscopy Environment.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openmicroscopy.shoola.keywords;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.util.NoSuchElementException;
import javax.swing.JPanel;
import org.robotframework.abbot.finder.BasicFinder;
import org.robotframework.abbot.finder.ComponentNotFoundException;
import org.robotframework.abbot.finder.Matcher;
import org.robotframework.abbot.finder.MultipleComponentsFoundException;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
/**
* Robot Framework SwingLibrary keyword library offering methods for checking thumbnails.
* @author m.t.b.carroll@dundee.ac.uk
* @since 4.4.9
*/
public class ThumbnailCheckLibrary
{
/** Allow Robot Framework to instantiate this library only once. */
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";
/**
* An iterator over the integer pixel values of a rendered image,
* first increasing <em>x</em>, then <em>y</em> when <em>x</em> wraps back to 0.
* This is written so as to be scalable over arbitrary image sizes
* and to not cause heap allocations during the iteration.
* @author m.t.b.carroll@dundee.ac.uk
* @since 4.4.9
*/
private static class IteratorIntPixel {
final Raster raster;
final int width;
final int height;
final int[] pixel = new int[1];
int x = 0;
int y = 0;
/**
* Create a new pixel iterator for the given image.
* The image is assumed to be of a type that packs data for each pixel into an <code>int</code>.
* @param image the image over whose pixels to iterate
*/
IteratorIntPixel(RenderedImage image) {
this.raster = image.getData();
this.width = image.getWidth();
this.height = image.getHeight();
}
/**
* @return if any pixels remain to be read with {@link #next()}
*/
boolean hasNext() {
return y < height;
}
/**
* @return the next pixel
* @throws NoSuchElementException if no more pixels remain
*/
int next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
raster.getDataElements(x, y, pixel);
if (++x == width) {
x = 0;
++y;
}
return pixel[0];
}
}
/**
* Find the thumbnail <code>Component</code> in the AWT hierarchy.
* @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas
* @param imageFilename the name of the image whose thumbnail is to be rasterized
* @return the AWT <code>Component</code> for the thumbnail
* @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name
* @throws ComponentNotFoundException if no thumbnails are for the given image name
*/
private static Component componentFinder(final String panelType, final String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
return new BasicFinder().find(new Matcher() {
private final String soughtName = panelType + " for " + imageFilename;
public boolean matches(Component component) {
return component instanceof JPanel && this.soughtName.equals(component.getName());
}});
}
/**
* Convert the thumbnail for the image of the given filename into rasterized pixel data.
* Each pixel is represented by an <code>int</code>.
* @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas
* @param imageFilename the name of the image whose thumbnail is to be rasterized
* @return the image on the thumbnail
* @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name
* @throws ComponentNotFoundException if no thumbnails are for the given image name
*/
private static RenderedImage captureImage(final String panelType, final String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
final JPanel thumbnail = (JPanel) componentFinder(panelType, imageFilename);
final int width = thumbnail.getWidth();
final int height = thumbnail.getHeight();
final BufferedImage image = new BufferedImage(width, height, StaticFieldLibrary.IMAGE_TYPE);
final Graphics2D graphics = image.createGraphics();
if (graphics == null) {
throw new RuntimeException("thumbnail is not displayable");
}
thumbnail.paint(graphics);
graphics.dispose();
return image;
}
/**
* <table>
* <td>Get Thumbnail Border Color</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the color of the thumbnail's corner pixel
* @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name
* @throws ComponentNotFoundException if no thumbnails exist for the given name
*/
public String getThumbnailBorderColor(String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
final RenderedImage image = captureImage("image node", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
if (!pixels.hasNext()) {
throw new RuntimeException("image node has no pixels");
}
return Integer.toHexString(pixels.next());
}
/**
* <table>
* <td>Is Thumbnail Monochromatic</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return if the image's thumbnail canvas is solidly one color
* @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name
* @throws ComponentNotFoundException if no thumbnails exist for the given name
*/
public boolean isThumbnailMonochromatic(String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
final RenderedImage image = captureImage("thumbnail", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
if (!pixels.hasNext()) {
throw new RuntimeException("thumbnail image has no pixels");
}
final int oneColor = pixels.next();
while (pixels.hasNext()) {
if (pixels.next() != oneColor) {
return false;
}
}
return true;
}
/**
* <table>
* <td>Get Thumbnail Hash</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the hash of the thumbnail canvas image
* @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name
* @throws ComponentNotFoundException if no thumbnails exist for the given name
*/
public String getThumbnailHash(String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
final RenderedImage image = captureImage("thumbnail", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
final Hasher hasher = Hashing.goodFastHash(128).newHasher();
while (pixels.hasNext()) {
hasher.putInt(pixels.next());
}
return hasher.hash().toString();
}
/**
* <table>
* <td>Get Name Of Thumbnail For Image</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the return value of the corresponding <code>ThumbnailCanvas.getName()</code>
* @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name
* @throws ComponentNotFoundException if no thumbnails exist for the given name
*/
public String getNameOfThumbnailForImage(final String imageFilename)
throws ComponentNotFoundException, MultipleComponentsFoundException {
return componentFinder("thumbnail", imageFilename).getName();
}
}
| jballanc/openmicroscopy | components/tests/ui/library/java/src/org/openmicroscopy/shoola/keywords/ThumbnailCheckLibrary.java | Java | gpl-2.0 | 9,339 |
package com.laytonsmith.abstraction;
import com.laytonsmith.abstraction.enums.MCDisplaySlot;
import java.util.Set;
public interface MCScoreboard {
public void clearSlot(MCDisplaySlot slot);
public MCObjective getObjective(MCDisplaySlot slot);
public MCObjective getObjective(String name);
/**
*
* @return Set of all objectives on this scoreboard
*/
public Set<MCObjective> getObjectives();
public Set<MCObjective> getObjectivesByCriteria(String criteria);
/**
*
* @return Set of all players tracked by this scoreboard
*/
public Set<String> getEntries();
public MCTeam getPlayerTeam(MCOfflinePlayer player);
public Set<MCScore> getScores(String entry);
public MCTeam getTeam(String teamName);
public Set<MCTeam> getTeams();
public MCObjective registerNewObjective(String name, String criteria);
public MCTeam registerNewTeam(String name);
public void resetScores(String entry);
}
| Murreey/CommandHelper | src/main/java/com/laytonsmith/abstraction/MCScoreboard.java | Java | gpl-3.0 | 908 |
package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemTool;
import cn.nukkit.level.Level;
import cn.nukkit.level.sound.NoteBoxSound;
import cn.nukkit.network.protocol.BlockEventPacket;
/**
* Created by Snake1999 on 2016/1/17.
* Package cn.nukkit.block in project nukkit.
*/
public class BlockNoteblock extends BlockSolid {
public BlockNoteblock() {
this(0);
}
public BlockNoteblock(int meta) {
super(meta);
}
@Override
public String getName() {
return "Note Block";
}
@Override
public int getId() {
return NOTEBLOCK;
}
@Override
public int getToolType() {
return ItemTool.TYPE_AXE;
}
@Override
public double getHardness() {
return 0.8D;
}
@Override
public double getResistance() {
return 4D;
}
public boolean canBeActivated() {
return true;
}
public int getStrength() {
return this.meta;
}
public void increaseStrength() {
if (this.meta < 24) {
this.meta++;
} else {
this.meta = 0;
}
}
public int getInstrument() {
Block below = this.down();
switch (below.getId()) {
case WOODEN_PLANK:
case NOTEBLOCK:
case CRAFTING_TABLE:
return NoteBoxSound.INSTRUMENT_BASS;
case SAND:
case SANDSTONE:
case SOUL_SAND:
return NoteBoxSound.INSTRUMENT_TABOUR;
case GLASS:
case GLASS_PANEL:
case GLOWSTONE_BLOCK:
return NoteBoxSound.INSTRUMENT_CLICK;
case COAL_ORE:
case DIAMOND_ORE:
case EMERALD_ORE:
case GLOWING_REDSTONE_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
return NoteBoxSound.INSTRUMENT_BASS_DRUM;
default:
return NoteBoxSound.INSTRUMENT_PIANO;
}
}
public void emitSound() {
BlockEventPacket pk = new BlockEventPacket();
pk.x = (int) this.x;
pk.y = (int) this.y;
pk.z = (int) this.z;
pk.case1 = this.getInstrument();
pk.case2 = this.getStrength();
this.getLevel().addChunkPacket((int) this.x >> 4, (int) this.z >> 4, pk);
this.getLevel().addSound(new NoteBoxSound(this, this.getInstrument(), this.getStrength()));
}
public boolean onActivate(Item item) {
return this.onActivate(item, null);
}
public boolean onActivate(Item item, Player player) {
Block up = this.up();
if (up.getId() == Block.AIR) {
this.increaseStrength();
this.emitSound();
return true;
} else {
return false;
}
}
@Override
public int onUpdate(int type) {
if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) {
//TODO: redstone
}
return 0;
}
}
| yescallop/Nukkit | src/main/java/cn/nukkit/block/BlockNoteblock.java | Java | gpl-3.0 | 3,101 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.cts.verifier.p2p.testcase;
import java.util.ArrayList;
import java.util.List;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener;
import android.util.Log;
/**
* The utility class for testing
* android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener callback function.
*/
public class DnsSdResponseListenerTest extends ListenerTest
implements DnsSdServiceResponseListener {
private static final String TAG = "DnsSdResponseListenerTest";
public static final List<ListenerArgument> NO_DNS_PTR
= new ArrayList<ListenerArgument>();
public static final List<ListenerArgument> ALL_DNS_PTR
= new ArrayList<ListenerArgument>();
public static final List<ListenerArgument> IPP_DNS_PTR
= new ArrayList<ListenerArgument>();
public static final List<ListenerArgument> AFP_DNS_PTR
= new ArrayList<ListenerArgument>();
/**
* The target device address.
*/
private String mTargetAddr;
static {
initialize();
}
public DnsSdResponseListenerTest(String targetAddr) {
mTargetAddr = targetAddr;
}
@Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
Log.d(TAG, instanceName + " " + registrationType +
" received from " + srcDevice.deviceAddress);
/*
* Check only the response from the target device.
* The response from other devices are ignored.
*/
if (srcDevice.deviceAddress.equalsIgnoreCase(mTargetAddr)) {
receiveCallback(new Argument(instanceName, registrationType));
}
}
private static void initialize() {
String ippInstanceName = "MyPrinter";
String ippRegistrationType = "_ipp._tcp.local.";
String afpInstanceName = "Example";
String afpRegistrationType = "_afpovertcp._tcp.local.";
IPP_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType));
AFP_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType));
ALL_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType));
ALL_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType));
}
/**
* The container of the argument of {@link #onDnsSdServiceAvailable}.
*/
static class Argument extends ListenerArgument {
private String mInstanceName;
private String mRegistrationType;
/**
* Set the argument of {@link #onDnsSdServiceAvailable}.
*
* @param instanceName instance name.
* @param registrationType registration type.
*/
Argument(String instanceName, String registrationType) {
mInstanceName = instanceName;
mRegistrationType = registrationType;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Argument)) {
return false;
}
Argument arg = (Argument)obj;
return equals(mInstanceName, arg.mInstanceName) &&
equals(mRegistrationType, arg.mRegistrationType);
}
private boolean equals(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[type=dns_ptr instant_name=");
sb.append(mInstanceName);
sb.append(" registration type=");
sb.append(mRegistrationType);
sb.append("\n");
return "instanceName=" + mInstanceName +
" registrationType=" + mRegistrationType;
}
}
}
| s20121035/rk3288_android5.1_repo | cts/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/DnsSdResponseListenerTest.java | Java | gpl-3.0 | 4,616 |
/* Copyright (c) 2001-2008, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/* $Id: SqlTool.java,v 1.72 2007/06/29 12:23:47 unsaved Exp $ */
/**
* Sql Tool. A command-line and/or interactive SQL tool.
* (Note: For every Javadoc block comment, I'm using a single blank line
* immediately after the description, just like's Sun's examples in
* their Coding Conventions document).
*
* See JavaDocs for the main method for syntax of how to run.
* This class is mostly used in a static (a.o.t. object) way, because most
* of the work is done in the static main class.
* This class should be refactored so that the main work is done in an
* object method, and the static main invokes the object method.
* Then programmatic users could use instances of this class in the normal
* Java way.
*
* @see #main()
* @version $Revision: 1.72 $
* @author Blaine Simpson unsaved@users
*/
public class SqlTool {
private static final String DEFAULT_RCFILE =
System.getProperty("user.home") + "/sqltool.rc";
// N.b. the following is static!
private static String revnum = null;
public static final int SQLTOOLERR_EXITVAL = 1;
public static final int SYNTAXERR_EXITVAL = 11;
public static final int RCERR_EXITVAL = 2;
public static final int SQLERR_EXITVAL = 3;
public static final int IOERR_EXITVAL = 4;
public static final int FILEERR_EXITVAL = 5;
public static final int INPUTERR_EXITVAL = 6;
public static final int CONNECTERR_EXITVAL = 7;
/**
* The configuration identifier to use when connection parameters are
* specified on the command line
*/
private static String CMDLINE_ID = "cmdline";
static private SqltoolRB rb = null;
// Must use a shared static RB object, since we need to get messages
// inside of static methods.
// This means that the locale will be set the first time this class
// is accessed. Subsequent calls will not update the RB if the locale
// changes (could have it check and reload the RB if this becomes an
// issue).
static {
revnum = "333";
try {
rb = new SqltoolRB();
rb.validate();
rb.setMissingPosValueBehavior(
ValidatingResourceBundle.NOOP_BEHAVIOR);
rb.setMissingPropertyBehavior(
ValidatingResourceBundle.NOOP_BEHAVIOR);
} catch (RuntimeException re) {
System.err.println("Failed to initialize resource bundle");
throw re;
}
}
public static String LS = System.getProperty("line.separator");
/** Utility nested class for internal use. */
private static class BadCmdline extends Exception {
static final long serialVersionUID = -2134764796788108325L;
BadCmdline() {}
}
/** Utility object for internal use. */
private static BadCmdline bcl = new BadCmdline();
/** For trapping of exceptions inside this class.
* These are always handled inside this class.
*/
private static class PrivateException extends Exception {
static final long serialVersionUID = -7765061479594523462L;
PrivateException() {
super();
}
PrivateException(String s) {
super(s);
}
}
public static class SqlToolException extends Exception {
static final long serialVersionUID = 1424909871915188519L;
int exitValue = 1;
SqlToolException(String message, int exitValue) {
super(message);
this.exitValue = exitValue;
}
SqlToolException(int exitValue, String message) {
this(message, exitValue);
}
SqlToolException(int exitValue) {
super();
this.exitValue = exitValue;
}
}
/**
* Prompt the user for a password.
*
* @param username The user the password is for
* @return The password the user entered
*/
private static String promptForPassword(String username)
throws PrivateException {
BufferedReader console;
String password;
password = null;
try {
console = new BufferedReader(new InputStreamReader(System.in));
// Prompt for password
System.out.print(rb.getString(SqltoolRB.PASSWORDFOR_PROMPT,
RCData.expandSysPropVars(username)));
// Read the password from the command line
password = console.readLine();
if (password == null) {
password = "";
} else {
password = password.trim();
}
} catch (IOException e) {
throw new PrivateException(e.getMessage());
}
return password;
}
/**
* Parses a comma delimited string of name value pairs into a
* <code>Map</code> object.
*
* @param varString The string to parse
* @param varMap The map to save the paired values into
* @param lowerCaseKeys Set to <code>true</code> if the map keys should be
* converted to lower case
*/
private static void varParser(String varString, Map varMap,
boolean lowerCaseKeys)
throws PrivateException {
int equals;
String var;
String val;
String[] allvars;
if ((varMap == null) || (varString == null)) {
throw new IllegalArgumentException(
"varMap or varString are null in SqlTool.varParser call");
}
allvars = varString.split("\\s*,\\s*");
for (int i = 0; i < allvars.length; i++) {
equals = allvars[i].indexOf('=');
if (equals < 1) {
throw new PrivateException(
rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT));
}
var = allvars[i].substring(0, equals).trim();
val = allvars[i].substring(equals + 1).trim();
if (var.length() < 1) {
throw new PrivateException(
rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT));
}
if (lowerCaseKeys) {
var = var.toLowerCase();
}
varMap.put(var, val);
}
}
/**
* A static wrapper for objectMain, so that that method may be executed
* as a Java "program".
*
* Throws only RuntimExceptions or Errors, because this method is intended
* to System.exit() for all but disasterous system problems, for which
* the inconvenience of a a stack trace would be the least of your worries.
*
* If you don't want SqlTool to System.exit(), then use the method
* objectMain() instead of this method.
*
* @see objectMain(String[])
*/
public static void main(String[] args) {
try {
SqlTool.objectMain(args);
} catch (SqlToolException fr) {
if (fr.getMessage() != null) {
System.err.println(fr.getMessage());
}
System.exit(fr.exitValue);
}
System.exit(0);
}
/**
* Connect to a JDBC Database and execute the commands given on
* stdin or in SQL file(s).
*
* This method is changed for HSQLDB 1.8.0.8 and 1.9.0.x to never
* System.exit().
*
* @param arg Run "java... org.hsqldb.util.SqlTool --help" for syntax.
* @throws SqlToolException Upon any fatal error, with useful
* reason as the exception's message.
*/
static public void objectMain(String[] arg) throws SqlToolException {
/*
* The big picture is, we parse input args; load a RCData;
* get a JDBC Connection with the RCData; instantiate and
* execute as many SqlFiles as we need to.
*/
String rcFile = null;
File tmpFile = null;
String sqlText = null;
String driver = null;
String targetDb = null;
String varSettings = null;
boolean debug = false;
File[] scriptFiles = null;
int i = -1;
boolean listMode = false;
boolean interactive = false;
boolean noinput = false;
boolean noautoFile = false;
boolean autoCommit = false;
Boolean coeOverride = null;
Boolean stdinputOverride = null;
String rcParams = null;
String rcUrl = null;
String rcUsername = null;
String rcPassword = null;
String rcCharset = null;
String rcTruststore = null;
Map rcFields = null;
String parameter;
try {
while ((i + 1 < arg.length) && arg[i + 1].startsWith("--")) {
i++;
if (arg[i].length() == 2) {
break; // "--"
}
parameter = arg[i].substring(2).toLowerCase();
if (parameter.equals("help")) {
System.out.println(rb.getString(SqltoolRB.SQLTOOL_SYNTAX,
revnum, RCData.DEFAULT_JDBC_DRIVER));
return;
}
if (parameter.equals("abortonerr")) {
if (coeOverride != null) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(
SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE));
}
coeOverride = Boolean.FALSE;
} else if (parameter.equals("continueonerr")) {
if (coeOverride != null) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(
SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE));
}
coeOverride = Boolean.TRUE;
} else if (parameter.equals("list")) {
listMode = true;
} else if (parameter.equals("rcfile")) {
if (++i == arg.length) {
throw bcl;
}
rcFile = arg[i];
} else if (parameter.equals("setvar")) {
if (++i == arg.length) {
throw bcl;
}
varSettings = arg[i];
} else if (parameter.equals("sql")) {
noinput = true; // but turn back on if file "-" specd.
if (++i == arg.length) {
throw bcl;
}
sqlText = arg[i];
} else if (parameter.equals("debug")) {
debug = true;
} else if (parameter.equals("noautofile")) {
noautoFile = true;
} else if (parameter.equals("autocommit")) {
autoCommit = true;
} else if (parameter.equals("stdinput")) {
noinput = false;
stdinputOverride = Boolean.TRUE;
} else if (parameter.equals("noinput")) {
noinput = true;
stdinputOverride = Boolean.FALSE;
} else if (parameter.equals("driver")) {
if (++i == arg.length) {
throw bcl;
}
driver = arg[i];
} else if (parameter.equals("inlinerc")) {
if (++i == arg.length) {
throw bcl;
}
rcParams = arg[i];
} else {
throw bcl;
}
}
if (!listMode) {
// If an inline RC file was specified, don't worry about the targetDb
if (rcParams == null) {
if (++i == arg.length) {
throw bcl;
}
targetDb = arg[i];
}
}
int scriptIndex = 0;
if (sqlText != null) {
try {
tmpFile = File.createTempFile("sqltool-", ".sql");
//(new java.io.FileWriter(tmpFile)).write(sqlText);
java.io.FileWriter fw = new java.io.FileWriter(tmpFile);
try {
fw.write("/* " + (new java.util.Date()) + ". "
+ SqlTool.class.getName()
+ " command-line SQL. */" + LS + LS);
fw.write(sqlText + LS);
fw.flush();
} finally {
fw.close();
}
} catch (IOException ioe) {
throw new SqlToolException(IOERR_EXITVAL,
rb.getString(SqltoolRB.SQLTEMPFILE_FAIL,
ioe.toString()));
}
}
if (stdinputOverride != null) {
noinput = !stdinputOverride.booleanValue();
}
interactive = (!noinput) && (arg.length <= i + 1);
if (arg.length == i + 2 && arg[i + 1].equals("-")) {
if (stdinputOverride == null) {
noinput = false;
}
} else if (arg.length > i + 1) {
// I.e., if there are any SQL files specified.
scriptFiles = new File[arg.length - i - 1
+ ((stdinputOverride == null
||!stdinputOverride.booleanValue()) ? 0 : 1)];
if (debug) {
System.err.println("scriptFiles has "
+ scriptFiles.length + " elements");
}
while (i + 1 < arg.length) {
scriptFiles[scriptIndex++] = new File(arg[++i]);
}
if (stdinputOverride != null
&& stdinputOverride.booleanValue()) {
scriptFiles[scriptIndex++] = null;
noinput = true;
}
}
} catch (BadCmdline bcl) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(SqltoolRB.SQLTOOL_SYNTAX,
revnum, RCData.DEFAULT_JDBC_DRIVER));
}
RCData conData = null;
// Use the inline RC file if it was specified
if (rcParams != null) {
rcFields = new HashMap();
try {
varParser(rcParams, rcFields, true);
} catch (PrivateException e) {
throw new SqlToolException(SYNTAXERR_EXITVAL, e.getMessage());
}
rcUrl = (String) rcFields.remove("url");
rcUsername = (String) rcFields.remove("user");
rcCharset = (String) rcFields.remove("charset");
rcTruststore = (String) rcFields.remove("truststore");
rcPassword = (String) rcFields.remove("password");
// Don't ask for password if what we have already is invalid!
if (rcUrl == null || rcUrl.length() < 1)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.RCDATA_INLINEURL_MISSING));
if (rcUsername == null || rcUsername.length() < 1)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.RCDATA_INLINEUSERNAME_MISSING));
if (rcPassword != null && rcPassword.length() > 0)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.RCDATA_PASSWORD_VISIBLE));
if (rcFields.size() > 0) {
throw new SqlToolException(INPUTERR_EXITVAL,
rb.getString(SqltoolRB.RCDATA_INLINE_EXTRAVARS,
rcFields.keySet().toString()));
}
if (rcPassword == null) try {
rcPassword = promptForPassword(rcUsername);
} catch (PrivateException e) {
throw new SqlToolException(INPUTERR_EXITVAL,
rb.getString(SqltoolRB.PASSWORD_READFAIL,
e.getMessage()));
}
try {
conData = new RCData(CMDLINE_ID, rcUrl, rcUsername,
rcPassword, driver, rcCharset,
rcTruststore);
} catch (Exception e) {
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.RCDATA_GENFROMVALUES_FAIL, e.getMessage()));
}
} else {
try {
conData = new RCData(new File((rcFile == null)
? DEFAULT_RCFILE
: rcFile), targetDb);
} catch (Exception e) {
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.CONNDATA_RETRIEVAL_FAIL,
targetDb, e.getMessage()));
}
}
if (listMode) {
return;
}
if (debug) {
conData.report();
}
Connection conn = null;
try {
conn = conData.getConnection(
driver, System.getProperty("sqlfile.charset"),
System.getProperty("javax.net.ssl.trustStore"));
conn.setAutoCommit(autoCommit);
DatabaseMetaData md = null;
if (interactive && (md = conn.getMetaData()) != null) {
System.out.println(
rb.getString(SqltoolRB.JDBC_ESTABLISHED,
md.getDatabaseProductName(),
md.getDatabaseProductVersion(),
md.getUserName()));
}
} catch (Exception e) {
//e.printStackTrace();
// Let's not continue as if nothing is wrong.
throw new SqlToolException(CONNECTERR_EXITVAL,
rb.getString(SqltoolRB.CONNECTION_FAIL,
conData.url, conData.username, e.getMessage()));
}
File[] emptyFileArray = {};
File[] singleNullFileArray = { null };
File autoFile = null;
if (interactive &&!noautoFile) {
autoFile = new File(System.getProperty("user.home")
+ "/auto.sql");
if ((!autoFile.isFile()) ||!autoFile.canRead()) {
autoFile = null;
}
}
if (scriptFiles == null) {
// I.e., if no SQL files given on command-line.
// Input file list is either nothing or {null} to read stdin.
scriptFiles = (noinput ? emptyFileArray
: singleNullFileArray);
}
int numFiles = scriptFiles.length;
if (tmpFile != null) {
numFiles += 1;
}
if (autoFile != null) {
numFiles += 1;
}
SqlFile[] sqlFiles = new SqlFile[numFiles];
Map userVars = new HashMap();
if (varSettings != null) try {
varParser(varSettings, userVars, false);
} catch (PrivateException pe) {
throw new SqlToolException(RCERR_EXITVAL, pe.getMessage());
}
// We print version before execing this one.
int interactiveFileIndex = -1;
try {
int fileIndex = 0;
if (autoFile != null) {
sqlFiles[fileIndex++] = new SqlFile(autoFile, false,
userVars);
}
if (tmpFile != null) {
sqlFiles[fileIndex++] = new SqlFile(tmpFile, false, userVars);
}
for (int j = 0; j < scriptFiles.length; j++) {
if (interactiveFileIndex < 0 && interactive) {
interactiveFileIndex = fileIndex;
}
sqlFiles[fileIndex++] = new SqlFile(scriptFiles[j],
interactive, userVars);
}
} catch (IOException ioe) {
try {
conn.close();
} catch (Exception e) {}
throw new SqlToolException(FILEERR_EXITVAL, ioe.getMessage());
}
try {
for (int j = 0; j < sqlFiles.length; j++) {
if (j == interactiveFileIndex) {
System.out.print("SqlTool v. " + revnum
+ ". ");
}
sqlFiles[j].execute(conn, coeOverride);
}
// Following two Exception types are handled properly inside of
// SqlFile. We just need to return an appropriate error status.
} catch (SqlToolError ste) {
throw new SqlToolException(SQLTOOLERR_EXITVAL);
} catch (SQLException se) {
// SqlTool will only throw an SQLException if it is in
// "\c false" mode.
throw new SqlToolException(SQLERR_EXITVAL);
} finally {
try {
conn.close();
} catch (Exception e) {}
}
// Taking file removal out of final block because this is good debug
// info to keep around if the program aborts.
if (tmpFile != null && !tmpFile.delete()) {
System.err.println(conData.url + rb.getString(
SqltoolRB.TEMPFILE_REMOVAL_FAIL, tmpFile.toString()));
}
}
}
| danielbejaranogonzalez/Mobile-Network-Designer | db/hsqldb/src/org/hsqldb/util/SqlTool.java | Java | gpl-3.0 | 23,912 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.text.tx3g;
import com.google.android.exoplayer.text.Cue;
import com.google.android.exoplayer.text.Subtitle;
import com.google.android.exoplayer.text.SubtitleParser;
import com.google.android.exoplayer.util.MimeTypes;
import com.google.android.exoplayer.util.ParsableByteArray;
/**
* A {@link SubtitleParser} for tx3g.
* <p>
* Currently only supports parsing of a single text track.
*/
public final class Tx3gParser implements SubtitleParser {
private final ParsableByteArray parsableByteArray;
public Tx3gParser() {
parsableByteArray = new ParsableByteArray();
}
@Override
public boolean canParse(String mimeType) {
return MimeTypes.APPLICATION_TX3G.equals(mimeType);
}
@Override
public Subtitle parse(byte[] bytes, int offset, int length) {
parsableByteArray.reset(bytes, length);
int textLength = parsableByteArray.readUnsignedShort();
if (textLength == 0) {
return Tx3gSubtitle.EMPTY;
}
String cueText = parsableByteArray.readString(textLength);
return new Tx3gSubtitle(new Cue(cueText));
}
}
| Lee-Wills/-tv | mmd/library/src/main/java/com/google/android/exoplayer/text/tx3g/Tx3gParser.java | Java | gpl-3.0 | 1,720 |
/*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.event.terraingen;
import java.util.Random;
import net.minecraft.block.BlockSapling;
import net.minecraft.block.state.IBlockState;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.fml.common.eventhandler.Event.HasResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.world.WorldEvent;
/**
* SaplingGrowTreeEvent is fired when a sapling grows into a tree.<br>
* This event is fired during sapling growth in
* {@link BlockSapling#generateTree(World, BlockPos, IBlockState, Random)}.<br>
* <br>
* {@link #pos} contains the coordinates of the growing sapling. <br>
* {@link #rand} contains an instance of Random for use. <br>
* <br>
* This event is not {@link Cancelable}.<br>
* <br>
* This event has a result. {@link HasResult} <br>
* This result determines if the sapling is allowed to grow. <br>
* <br>
* This event is fired on the {@link MinecraftForge#TERRAIN_GEN_BUS}.<br>
**/
@HasResult
public class SaplingGrowTreeEvent extends WorldEvent
{
private final BlockPos pos;
private final Random rand;
public SaplingGrowTreeEvent(World world, Random rand, BlockPos pos)
{
super(world);
this.rand = rand;
this.pos = pos;
}
public BlockPos getPos()
{
return pos;
}
public Random getRand()
{
return rand;
}
} | Severed-Infinity/technium | build/tmp/recompileMc/sources/net/minecraftforge/event/terraingen/SaplingGrowTreeEvent.java | Java | gpl-3.0 | 2,229 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.generalmedical.vo;
/**
* Linked to core.clinical.EpworthSleepAssessment business object (ID: 1003100055).
*/
public class EpworthSleepAssessmentVo extends ims.core.clinical.vo.EpworthSleepAssessmentRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public EpworthSleepAssessmentVo()
{
}
public EpworthSleepAssessmentVo(Integer id, int version)
{
super(id, version);
}
public EpworthSleepAssessmentVo(ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep());
this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep());
this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean = null;
if(map != null)
bean = (ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("CHANCEOFSLEEP"))
return getChanceOfSleep();
if(fieldName.equals("SLEEPSCORE"))
return getSleepScore();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getChanceOfSleepIsNotNull()
{
return this.chanceofsleep != null;
}
public ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep getChanceOfSleep()
{
return this.chanceofsleep;
}
public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep value)
{
this.isValidated = false;
this.chanceofsleep = value;
}
public boolean getSleepScoreIsNotNull()
{
return this.sleepscore != null;
}
public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore()
{
return this.sleepscore;
}
public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value)
{
this.isValidated = false;
this.sleepscore = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
EpworthSleepAssessmentVo clone = new EpworthSleepAssessmentVo(this.id, this.version);
if(this.chanceofsleep == null)
clone.chanceofsleep = null;
else
clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep)this.chanceofsleep.clone();
if(this.sleepscore == null)
clone.sleepscore = null;
else
clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(EpworthSleepAssessmentVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A EpworthSleepAssessmentVo object cannot be compared an Object of type " + obj.getClass().getName());
}
EpworthSleepAssessmentVo compareObj = (EpworthSleepAssessmentVo)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getID_EpworthSleepAssessment() == null && compareObj.getID_EpworthSleepAssessment() != null)
return -1;
if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() == null)
return 1;
if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() != null)
retVal = this.getID_EpworthSleepAssessment().compareTo(compareObj.getID_EpworthSleepAssessment());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.chanceofsleep != null)
count++;
if(this.sleepscore != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 2;
}
protected ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep chanceofsleep;
protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore;
private boolean isValidated = false;
private boolean isBusy = false;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/EpworthSleepAssessmentVo.java | Java | agpl-3.0 | 7,901 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.vo.beans;
public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean
{
public MRSATreatmentVoBean()
{
}
public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean();
this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean();
this.treatmentnumber = vo.getTreatmentNumber();
this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean();
this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean();
this.treatmentnumber = vo.getTreatmentNumber();
this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection();
}
public ims.nursing.vo.MRSATreatmentVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.nursing.vo.MRSATreatmentVo vo = null;
if(map != null)
vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.nursing.vo.MRSATreatmentVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.framework.utils.beans.DateBean getStartDate()
{
return this.startdate;
}
public void setStartDate(ims.framework.utils.beans.DateBean value)
{
this.startdate = value;
}
public ims.framework.utils.beans.DateBean getRescreenDate()
{
return this.rescreendate;
}
public void setRescreenDate(ims.framework.utils.beans.DateBean value)
{
this.rescreendate = value;
}
public Integer getTreatmentNumber()
{
return this.treatmentnumber;
}
public void setTreatmentNumber(Integer value)
{
this.treatmentnumber = value;
}
public ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] getTreatmentDetails()
{
return this.treatmentdetails;
}
public void setTreatmentDetails(ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] value)
{
this.treatmentdetails = value;
}
private Integer id;
private int version;
private ims.framework.utils.beans.DateBean startdate;
private ims.framework.utils.beans.DateBean rescreendate;
private Integer treatmentnumber;
private ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] treatmentdetails;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/nursing/vo/beans/MRSATreatmentVoBean.java | Java | agpl-3.0 | 4,677 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.vo;
/**
* Linked to nursing.assessment.Transfers business object (ID: 1015100016).
*/
public class Transfers extends ims.nursing.assessment.vo.TransfersRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public Transfers()
{
}
public Transfers(Integer id, int version)
{
super(id, version);
}
public Transfers(ims.nursing.vo.beans.TransfersBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers());
this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.TransfersBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers());
this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.nursing.vo.beans.TransfersBean bean = null;
if(map != null)
bean = (ims.nursing.vo.beans.TransfersBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.nursing.vo.beans.TransfersBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("PATIENTTRANSFERS"))
return getPatientTransfers();
if(fieldName.equals("ASSISTANCEREQUIRED"))
return getAssistanceRequired();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getPatientTransfersIsNotNull()
{
return this.patienttransfers != null;
}
public ims.nursing.vo.lookups.Transfers getPatientTransfers()
{
return this.patienttransfers;
}
public void setPatientTransfers(ims.nursing.vo.lookups.Transfers value)
{
this.isValidated = false;
this.patienttransfers = value;
}
public boolean getAssistanceRequiredIsNotNull()
{
return this.assistancerequired != null;
}
public ims.nursing.vo.lookups.Ability getAssistanceRequired()
{
return this.assistancerequired;
}
public void setAssistanceRequired(ims.nursing.vo.lookups.Ability value)
{
this.isValidated = false;
this.assistancerequired = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
Transfers clone = new Transfers(this.id, this.version);
if(this.patienttransfers == null)
clone.patienttransfers = null;
else
clone.patienttransfers = (ims.nursing.vo.lookups.Transfers)this.patienttransfers.clone();
if(this.assistancerequired == null)
clone.assistancerequired = null;
else
clone.assistancerequired = (ims.nursing.vo.lookups.Ability)this.assistancerequired.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(Transfers.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A Transfers object cannot be compared an Object of type " + obj.getClass().getName());
}
Transfers compareObj = (Transfers)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getID_Transfers() == null && compareObj.getID_Transfers() != null)
return -1;
if(this.getID_Transfers() != null && compareObj.getID_Transfers() == null)
return 1;
if(this.getID_Transfers() != null && compareObj.getID_Transfers() != null)
retVal = this.getID_Transfers().compareTo(compareObj.getID_Transfers());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.patienttransfers != null)
count++;
if(this.assistancerequired != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 2;
}
protected ims.nursing.vo.lookups.Transfers patienttransfers;
protected ims.nursing.vo.lookups.Ability assistancerequired;
private boolean isValidated = false;
private boolean isBusy = false;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/nursing/vo/Transfers.java | Java | agpl-3.0 | 7,494 |
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo;
/**
* Linked to RefMan.CatsReferral business object (ID: 1004100035).
*/
public class CatsReferralForSessionManagementVo extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public CatsReferralForSessionManagementVo()
{
}
public CatsReferralForSessionManagementVo(Integer id, int version)
{
super(id, version);
}
public CatsReferralForSessionManagementVo(ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo();
this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(map);
this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(map);
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean = null;
if(map != null)
bean = (ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("REFERRALDETAILS"))
return getReferralDetails();
if(fieldName.equals("CURRENTSTATUS"))
return getCurrentStatus();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getReferralDetailsIsNotNull()
{
return this.referraldetails != null;
}
public ims.RefMan.vo.ReferralLetterForSessionManagementVo getReferralDetails()
{
return this.referraldetails;
}
public void setReferralDetails(ims.RefMan.vo.ReferralLetterForSessionManagementVo value)
{
this.isValidated = false;
this.referraldetails = value;
}
public boolean getCurrentStatusIsNotNull()
{
return this.currentstatus != null;
}
public ims.RefMan.vo.CatsReferralStatusLiteVo getCurrentStatus()
{
return this.currentstatus;
}
public void setCurrentStatus(ims.RefMan.vo.CatsReferralStatusLiteVo value)
{
this.isValidated = false;
this.currentstatus = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
CatsReferralForSessionManagementVo clone = new CatsReferralForSessionManagementVo(this.id, this.version);
if(this.referraldetails == null)
clone.referraldetails = null;
else
clone.referraldetails = (ims.RefMan.vo.ReferralLetterForSessionManagementVo)this.referraldetails.clone();
if(this.currentstatus == null)
clone.currentstatus = null;
else
clone.currentstatus = (ims.RefMan.vo.CatsReferralStatusLiteVo)this.currentstatus.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(CatsReferralForSessionManagementVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A CatsReferralForSessionManagementVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((CatsReferralForSessionManagementVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((CatsReferralForSessionManagementVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.referraldetails != null)
count++;
if(this.currentstatus != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 2;
}
protected ims.RefMan.vo.ReferralLetterForSessionManagementVo referraldetails;
protected ims.RefMan.vo.CatsReferralStatusLiteVo currentstatus;
private boolean isValidated = false;
private boolean isBusy = false;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/CatsReferralForSessionManagementVo.java | Java | agpl-3.0 | 5,952 |
/*
* Copyright 2014-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.serializers;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.LinkKey;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Kryo Serializer for {@link LinkKey}.
*/
public class LinkKeySerializer extends Serializer<LinkKey> {
/**
* Creates {@link LinkKey} serializer instance.
*/
public LinkKeySerializer() {
// non-null, immutable
super(false, true);
}
@Override
public void write(Kryo kryo, Output output, LinkKey object) {
kryo.writeClassAndObject(output, object.src());
kryo.writeClassAndObject(output, object.dst());
}
@Override
public LinkKey read(Kryo kryo, Input input, Class<LinkKey> type) {
ConnectPoint src = (ConnectPoint) kryo.readClassAndObject(input);
ConnectPoint dst = (ConnectPoint) kryo.readClassAndObject(input);
return LinkKey.linkKey(src, dst);
}
}
| opennetworkinglab/onos | core/store/serializers/src/main/java/org/onosproject/store/serializers/LinkKeySerializer.java | Java | apache-2.0 | 1,671 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.test.rest.yaml.section;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.yaml.YamlXContent;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Holds a REST test suite loaded from a specific yaml file.
* Supports a setup section and multiple test sections.
*/
public class ClientYamlTestSuite {
public static ClientYamlTestSuite parse(String api, Path file) throws IOException {
if (!Files.isRegularFile(file)) {
throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file");
}
String filename = file.getFileName().toString();
//remove the file extension
int i = filename.lastIndexOf('.');
if (i > 0) {
filename = filename.substring(0, i);
}
//our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break.
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
if (channel.size() == 0) {
throw new IllegalArgumentException("test suite file " + file.toString() + " is empty");
}
channel.read(bb, channel.size() - 1);
if (bb.get(0) != 10) {
throw new IOException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)");
}
}
try (XContentParser parser = YamlXContent.yamlXContent.createParser(ExecutableSection.XCONTENT_REGISTRY,
LoggingDeprecationHandler.INSTANCE, Files.newInputStream(file))) {
return parse(api, filename, parser);
} catch(Exception e) {
throw new IOException("Error parsing " + api + "/" + filename, e);
}
}
public static ClientYamlTestSuite parse(String api, String suiteName, XContentParser parser) throws IOException {
parser.nextToken();
assert parser.currentToken() == XContentParser.Token.START_OBJECT : "expected token to be START_OBJECT but was "
+ parser.currentToken();
ClientYamlTestSuite restTestSuite = new ClientYamlTestSuite(api, suiteName);
restTestSuite.setSetupSection(SetupSection.parseIfNext(parser));
restTestSuite.setTeardownSection(TeardownSection.parseIfNext(parser));
while(true) {
//the "---" section separator is not understood by the yaml parser. null is returned, same as when the parser is closed
//we need to somehow distinguish between a null in the middle of a test ("---")
// and a null at the end of the file (at least two consecutive null tokens)
if(parser.currentToken() == null) {
if (parser.nextToken() == null) {
break;
}
}
ClientYamlTestSection testSection = ClientYamlTestSection.parse(parser);
if (!restTestSuite.addTestSection(testSection)) {
throw new ParsingException(testSection.getLocation(), "duplicate test section [" + testSection.getName() + "]");
}
}
return restTestSuite;
}
private final String api;
private final String name;
private SetupSection setupSection;
private TeardownSection teardownSection;
private Set<ClientYamlTestSection> testSections = new TreeSet<>();
public ClientYamlTestSuite(String api, String name) {
this.api = api;
this.name = name;
}
public String getApi() {
return api;
}
public String getName() {
return name;
}
public String getPath() {
return api + "/" + name;
}
public SetupSection getSetupSection() {
return setupSection;
}
public void setSetupSection(SetupSection setupSection) {
this.setupSection = setupSection;
}
public TeardownSection getTeardownSection() {
return teardownSection;
}
public void setTeardownSection(TeardownSection teardownSection) {
this.teardownSection = teardownSection;
}
/**
* Adds a {@link org.elasticsearch.test.rest.yaml.section.ClientYamlTestSection} to the REST suite
* @return true if the test section was not already present, false otherwise
*/
public boolean addTestSection(ClientYamlTestSection testSection) {
return this.testSections.add(testSection);
}
public List<ClientYamlTestSection> getTestSections() {
return new ArrayList<>(testSections);
}
}
| qwerty4030/elasticsearch | test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java | Java | apache-2.0 | 5,796 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.shell.commands;
import java.util.Map.Entry;
import org.apache.accumulo.core.data.constraints.Constraint;
import org.apache.accumulo.shell.Shell;
import org.apache.accumulo.shell.Shell.Command;
import org.apache.accumulo.shell.ShellCommandException;
import org.apache.accumulo.shell.ShellCommandException.ErrorCode;
import org.apache.accumulo.shell.ShellOptions;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
public class ConstraintCommand extends Command {
protected Option namespaceOpt;
@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
throws Exception {
final String tableName;
final String namespace;
if (cl.hasOption(namespaceOpt.getOpt())) {
namespace = cl.getOptionValue(namespaceOpt.getOpt());
} else {
namespace = null;
}
if (cl.hasOption(OptUtil.tableOpt().getOpt()) || !shellState.getTableName().isEmpty()) {
tableName = OptUtil.getTableOpt(cl, shellState);
} else {
tableName = null;
}
int i;
switch (OptUtil.getAldOpt(cl)) {
case ADD:
for (String constraint : cl.getArgs()) {
if (namespace != null) {
if (!shellState.getAccumuloClient().namespaceOperations().testClassLoad(namespace,
constraint, Constraint.class.getName())) {
throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE,
"Servers are unable to load " + constraint + " as type "
+ Constraint.class.getName());
}
i = shellState.getAccumuloClient().namespaceOperations().addConstraint(namespace,
constraint);
shellState.getWriter().println("Added constraint " + constraint + " to namespace "
+ namespace + " with number " + i);
} else if (tableName != null && !tableName.isEmpty()) {
if (!shellState.getAccumuloClient().tableOperations().testClassLoad(tableName,
constraint, Constraint.class.getName())) {
throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE,
"Servers are unable to load " + constraint + " as type "
+ Constraint.class.getName());
}
i = shellState.getAccumuloClient().tableOperations().addConstraint(tableName,
constraint);
shellState.getWriter().println(
"Added constraint " + constraint + " to table " + tableName + " with number " + i);
} else {
throw new IllegalArgumentException("Please specify either a table or a namespace");
}
}
break;
case DELETE:
for (String constraint : cl.getArgs()) {
i = Integer.parseInt(constraint);
if (namespace != null) {
shellState.getAccumuloClient().namespaceOperations().removeConstraint(namespace, i);
shellState.getWriter()
.println("Removed constraint " + i + " from namespace " + namespace);
} else if (tableName != null) {
shellState.getAccumuloClient().tableOperations().removeConstraint(tableName, i);
shellState.getWriter().println("Removed constraint " + i + " from table " + tableName);
} else {
throw new IllegalArgumentException("Please specify either a table or a namespace");
}
}
break;
case LIST:
if (namespace != null) {
for (Entry<String,Integer> property : shellState.getAccumuloClient().namespaceOperations()
.listConstraints(namespace).entrySet()) {
shellState.getWriter().println(property.toString());
}
} else if (tableName != null) {
for (Entry<String,Integer> property : shellState.getAccumuloClient().tableOperations()
.listConstraints(tableName).entrySet()) {
shellState.getWriter().println(property.toString());
}
} else {
throw new IllegalArgumentException("Please specify either a table or a namespace");
}
}
return 0;
}
@Override
public String description() {
return "adds, deletes, or lists constraints for a table";
}
@Override
public int numArgs() {
return Shell.NO_FIXED_ARG_LENGTH_CHECK;
}
@Override
public String usage() {
return getName() + " <constraint>{ <constraint>}";
}
@Override
public Options getOptions() {
final Options o = new Options();
o.addOptionGroup(OptUtil.addListDeleteGroup("constraint"));
OptionGroup grp = new OptionGroup();
grp.addOption(OptUtil.tableOpt("table to add, delete, or list constraints for"));
namespaceOpt = new Option(ShellOptions.namespaceOption, "namespace", true,
"name of a namespace to operate on");
namespaceOpt.setArgName("namespace");
grp.addOption(namespaceOpt);
o.addOptionGroup(grp);
return o;
}
}
| milleruntime/accumulo | shell/src/main/java/org/apache/accumulo/shell/commands/ConstraintCommand.java | Java | apache-2.0 | 5,893 |
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.util.PairFunction;
import com.intellij.util.containers.Convertor;
import javax.swing.*;
import javax.swing.table.TableModel;
import java.util.ListIterator;
public class TableSpeedSearch extends SpeedSearchBase<JTable> {
private static final PairFunction<Object, Cell, String> TO_STRING = new PairFunction<Object, Cell, String>() {
public String fun(Object o, Cell cell) {
return o == null ? "" : o.toString();
}
};
private final PairFunction<Object, Cell, String> myToStringConvertor;
public TableSpeedSearch(JTable table) {
this(table, TO_STRING);
}
public TableSpeedSearch(JTable table, final Convertor<Object, String> toStringConvertor) {
this(table, new PairFunction<Object, Cell, String>() {
@Override
public String fun(Object o, Cell c) {
return toStringConvertor.convert(o);
}
});
}
public TableSpeedSearch(JTable table, final PairFunction<Object, Cell, String> toStringConvertor) {
super(table);
myToStringConvertor = toStringConvertor;
}
protected boolean isSpeedSearchEnabled() {
return !getComponent().isEditing() && super.isSpeedSearchEnabled();
}
@Override
protected ListIterator<Object> getElementIterator(int startingIndex) {
return new MyListIterator(startingIndex);
}
protected int getElementCount() {
final TableModel tableModel = myComponent.getModel();
return tableModel.getRowCount() * tableModel.getColumnCount();
}
protected void selectElement(Object element, String selectedText) {
final int index = ((Integer)element).intValue();
final TableModel model = myComponent.getModel();
final int row = index / model.getColumnCount();
final int col = index % model.getColumnCount();
myComponent.getSelectionModel().setSelectionInterval(row, row);
myComponent.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
TableUtil.scrollSelectionToVisible(myComponent);
}
protected int getSelectedIndex() {
final int row = myComponent.getSelectedRow();
final int col = myComponent.getSelectedColumn();
// selected row is not enough as we want to select specific cell in a large multi-column table
return row > -1 && col > -1 ? row * myComponent.getModel().getColumnCount() + col : -1;
}
protected Object[] getAllElements() {
throw new UnsupportedOperationException("Not implemented");
}
protected String getElementText(Object element) {
final int index = ((Integer)element).intValue();
final TableModel model = myComponent.getModel();
int row = myComponent.convertRowIndexToModel(index / model.getColumnCount());
int col = myComponent.convertColumnIndexToModel(index % model.getColumnCount());
Object value = model.getValueAt(row, col);
return myToStringConvertor.fun(value, new Cell(row, col));
}
private class MyListIterator implements ListIterator<Object> {
private int myCursor;
public MyListIterator(int startingIndex) {
final int total = getElementCount();
myCursor = startingIndex < 0 ? total : startingIndex;
}
public boolean hasNext() {
return myCursor < getElementCount();
}
public Object next() {
return myCursor++;
}
public boolean hasPrevious() {
return myCursor > 0;
}
public Object previous() {
return (myCursor--) - 1;
}
public int nextIndex() {
return myCursor;
}
public int previousIndex() {
return myCursor - 1;
}
public void remove() {
throw new AssertionError("Not Implemented");
}
public void set(Object o) {
throw new AssertionError("Not Implemented");
}
public void add(Object o) {
throw new AssertionError("Not Implemented");
}
}
}
| liveqmock/platform-tools-idea | platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java | Java | apache-2.0 | 4,403 |
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.web;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
/**
* A resolver for {@link Link links} to web endpoints.
*
* @author Andy Wilkinson
* @since 2.0.0
*/
public class EndpointLinksResolver {
private static final Log logger = LogFactory.getLog(EndpointLinksResolver.class);
private final Collection<? extends ExposableEndpoint<?>> endpoints;
/**
* Creates a new {@code EndpointLinksResolver} that will resolve links to the given
* {@code endpoints}.
* @param endpoints the endpoints
*/
public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints) {
this.endpoints = endpoints;
}
/**
* Creates a new {@code EndpointLinksResolver} that will resolve links to the given
* {@code endpoints} that are exposed beneath the given {@code basePath}.
* @param endpoints the endpoints
* @param basePath the basePath
*/
public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints,
String basePath) {
this.endpoints = endpoints;
if (logger.isInfoEnabled()) {
logger.info("Exposing " + endpoints.size()
+ " endpoint(s) beneath base path '" + basePath + "'");
}
}
/**
* Resolves links to the known endpoints based on a request with the given
* {@code requestUrl}.
* @param requestUrl the url of the request for the endpoint links
* @return the links
*/
public Map<String, Link> resolveLinks(String requestUrl) {
String normalizedUrl = normalizeRequestUrl(requestUrl);
Map<String, Link> links = new LinkedHashMap<>();
links.put("self", new Link(normalizedUrl));
for (ExposableEndpoint<?> endpoint : this.endpoints) {
if (endpoint instanceof ExposableWebEndpoint) {
collectLinks(links, (ExposableWebEndpoint) endpoint, normalizedUrl);
}
else if (endpoint instanceof PathMappedEndpoint) {
links.put(endpoint.getId(), createLink(normalizedUrl,
((PathMappedEndpoint) endpoint).getRootPath()));
}
}
return links;
}
private String normalizeRequestUrl(String requestUrl) {
if (requestUrl.endsWith("/")) {
return requestUrl.substring(0, requestUrl.length() - 1);
}
return requestUrl;
}
private void collectLinks(Map<String, Link> links, ExposableWebEndpoint endpoint,
String normalizedUrl) {
for (WebOperation operation : endpoint.getOperations()) {
links.put(operation.getId(), createLink(normalizedUrl, operation));
}
}
private Link createLink(String requestUrl, WebOperation operation) {
return createLink(requestUrl, operation.getRequestPredicate().getPath());
}
private Link createLink(String requestUrl, String path) {
return new Link(requestUrl + (path.startsWith("/") ? path : "/" + path));
}
}
| bclozel/spring-boot | spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java | Java | apache-2.0 | 3,528 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.yarn.api.ContainerManagementProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerState;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AsyncDispatcher;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.security.NMTokenIdentifier;
import org.apache.hadoop.yarn.server.api.ResourceTracker;
import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.LocalRMInterface;
import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationState;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.junit.After;
import org.junit.Before;
public abstract class BaseContainerManagerTest {
protected static RecordFactory recordFactory = RecordFactoryProvider
.getRecordFactory(null);
protected static FileContext localFS;
protected static File localDir;
protected static File localLogDir;
protected static File remoteLogDir;
protected static File tmpDir;
protected final NodeManagerMetrics metrics = NodeManagerMetrics.create();
public BaseContainerManagerTest() throws UnsupportedFileSystemException {
localFS = FileContext.getLocalFSFileContext();
localDir =
new File("target", this.getClass().getSimpleName() + "-localDir")
.getAbsoluteFile();
localLogDir =
new File("target", this.getClass().getSimpleName() + "-localLogDir")
.getAbsoluteFile();
remoteLogDir =
new File("target", this.getClass().getSimpleName() + "-remoteLogDir")
.getAbsoluteFile();
tmpDir = new File("target", this.getClass().getSimpleName() + "-tmpDir");
}
protected static Log LOG = LogFactory
.getLog(BaseContainerManagerTest.class);
protected static final int HTTP_PORT = 5412;
protected Configuration conf = new YarnConfiguration();
protected Context context = new NMContext(new NMContainerTokenSecretManager(
conf), new NMTokenSecretManagerInNM()) {
public int getHttpPort() {
return HTTP_PORT;
};
};
protected ContainerExecutor exec;
protected DeletionService delSrvc;
protected String user = "nobody";
protected NodeHealthCheckerService nodeHealthChecker;
protected LocalDirsHandlerService dirsHandler;
protected final long DUMMY_RM_IDENTIFIER = 1234;
protected NodeStatusUpdater nodeStatusUpdater = new NodeStatusUpdaterImpl(
context, new AsyncDispatcher(), null, metrics) {
@Override
protected ResourceTracker getRMClient() {
return new LocalRMInterface();
};
@Override
protected void stopRMProxy() {
return;
}
@Override
protected void startStatusUpdater() {
return; // Don't start any updating thread.
}
@Override
public long getRMIdentifier() {
// There is no real RM registration, simulate and set RMIdentifier
return DUMMY_RM_IDENTIFIER;
}
};
protected ContainerManagerImpl containerManager = null;
protected ContainerExecutor createContainerExecutor() {
DefaultContainerExecutor exec = new DefaultContainerExecutor();
exec.setConf(conf);
return exec;
}
@Before
public void setup() throws IOException {
localFS.delete(new Path(localDir.getAbsolutePath()), true);
localFS.delete(new Path(tmpDir.getAbsolutePath()), true);
localFS.delete(new Path(localLogDir.getAbsolutePath()), true);
localFS.delete(new Path(remoteLogDir.getAbsolutePath()), true);
localDir.mkdir();
tmpDir.mkdir();
localLogDir.mkdir();
remoteLogDir.mkdir();
LOG.info("Created localDir in " + localDir.getAbsolutePath());
LOG.info("Created tmpDir in " + tmpDir.getAbsolutePath());
String bindAddress = "0.0.0.0:12345";
conf.set(YarnConfiguration.NM_ADDRESS, bindAddress);
conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir.getAbsolutePath());
conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogDir.getAbsolutePath());
conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1);
// Default delSrvc
delSrvc = createDeletionService();
delSrvc.init(conf);
exec = createContainerExecutor();
nodeHealthChecker = new NodeHealthCheckerService();
nodeHealthChecker.init(conf);
dirsHandler = nodeHealthChecker.getDiskHandler();
containerManager = createContainerManager(delSrvc);
((NMContext)context).setContainerManager(containerManager);
nodeStatusUpdater.init(conf);
containerManager.init(conf);
nodeStatusUpdater.start();
}
protected ContainerManagerImpl
createContainerManager(DeletionService delSrvc) {
return new ContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater,
metrics, new ApplicationACLsManager(conf), dirsHandler) {
@Override
public void
setBlockNewContainerRequests(boolean blockNewContainerRequests) {
// do nothing
}
@Override
protected void authorizeGetAndStopContainerRequest(ContainerId containerId,
Container container, boolean stopRequest, NMTokenIdentifier identifier) throws YarnException {
// do nothing
}
@Override
protected void authorizeUser(UserGroupInformation remoteUgi,
NMTokenIdentifier nmTokenIdentifier) {
// do nothing
}
@Override
protected void authorizeStartRequest(
NMTokenIdentifier nmTokenIdentifier,
ContainerTokenIdentifier containerTokenIdentifier) throws YarnException {
// do nothing
}
@Override
protected void updateNMTokenIdentifier(
NMTokenIdentifier nmTokenIdentifier) throws InvalidToken {
// Do nothing
}
@Override
public Map<String, ByteBuffer> getAuxServiceMetaData() {
Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>();
serviceData.put("AuxService1",
ByteBuffer.wrap("AuxServiceMetaData1".getBytes()));
serviceData.put("AuxService2",
ByteBuffer.wrap("AuxServiceMetaData2".getBytes()));
return serviceData;
}
};
}
protected DeletionService createDeletionService() {
return new DeletionService(exec) {
@Override
public void delete(String user, Path subDir, Path[] baseDirs) {
// Don't do any deletions.
LOG.info("Psuedo delete: user - " + user + ", subDir - " + subDir
+ ", baseDirs - " + baseDirs);
};
};
}
@After
public void tearDown() throws IOException, InterruptedException {
if (containerManager != null) {
containerManager.stop();
}
createContainerExecutor().deleteAsUser(user,
new Path(localDir.getAbsolutePath()), new Path[] {});
}
public static void waitForContainerState(ContainerManagementProtocol containerManager,
ContainerId containerID, ContainerState finalState)
throws InterruptedException, YarnException, IOException {
waitForContainerState(containerManager, containerID, finalState, 20);
}
public static void waitForContainerState(ContainerManagementProtocol containerManager,
ContainerId containerID, ContainerState finalState, int timeOutMax)
throws InterruptedException, YarnException, IOException {
List<ContainerId> list = new ArrayList<ContainerId>();
list.add(containerID);
GetContainerStatusesRequest request =
GetContainerStatusesRequest.newInstance(list);
ContainerStatus containerStatus =
containerManager.getContainerStatuses(request).getContainerStatuses()
.get(0);
int timeoutSecs = 0;
while (!containerStatus.getState().equals(finalState)
&& timeoutSecs++ < timeOutMax) {
Thread.sleep(1000);
LOG.info("Waiting for container to get into state " + finalState
+ ". Current state is " + containerStatus.getState());
containerStatus = containerManager.getContainerStatuses(request).getContainerStatuses().get(0);
}
LOG.info("Container state is " + containerStatus.getState());
Assert.assertEquals("ContainerState is not correct (timedout)",
finalState, containerStatus.getState());
}
static void waitForApplicationState(ContainerManagerImpl containerManager,
ApplicationId appID, ApplicationState finalState)
throws InterruptedException {
// Wait for app-finish
Application app =
containerManager.getContext().getApplications().get(appID);
int timeout = 0;
while (!(app.getApplicationState().equals(finalState))
&& timeout++ < 15) {
LOG.info("Waiting for app to reach " + finalState
+ ".. Current state is "
+ app.getApplicationState());
Thread.sleep(1000);
}
Assert.assertTrue("App is not in " + finalState + " yet!! Timedout!!",
app.getApplicationState().equals(finalState));
}
}
| tomatoKiller/Hadoop_Source_Learn | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java | Java | apache-2.0 | 11,919 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.proxy;
import io.airlift.configuration.Config;
import io.airlift.configuration.ConfigDescription;
import io.airlift.configuration.validation.FileExists;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.net.URI;
public class ProxyConfig
{
private URI uri;
private File sharedSecretFile;
@NotNull
public URI getUri()
{
return uri;
}
@Config("proxy.uri")
@ConfigDescription("URI of the remote Trino server")
public ProxyConfig setUri(URI uri)
{
this.uri = uri;
return this;
}
@NotNull
@FileExists
public File getSharedSecretFile()
{
return sharedSecretFile;
}
@Config("proxy.shared-secret-file")
@ConfigDescription("Shared secret file used for authenticating URIs")
public ProxyConfig setSharedSecretFile(File sharedSecretFile)
{
this.sharedSecretFile = sharedSecretFile;
return this;
}
}
| electrum/presto | service/trino-proxy/src/main/java/io/trino/proxy/ProxyConfig.java | Java | apache-2.0 | 1,534 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.mllp;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
/**
* Represents the component that manages {@link MllpEndpoint}.
*/
public class MllpComponent extends UriEndpointComponent {
public static final String MLLP_LOG_PHI_PROPERTY = "org.apache.camel.component.mllp.logPHI";
public MllpComponent() {
super(MllpEndpoint.class);
}
public MllpComponent(CamelContext context) {
super(context, MllpEndpoint.class);
}
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
MllpEndpoint endpoint = new MllpEndpoint(uri, this);
setProperties(endpoint, parameters);
// mllp://hostname:port
String hostPort;
// look for options
int optionsStartIndex = uri.indexOf('?');
if (-1 == optionsStartIndex) {
// No options - just get the host/port stuff
hostPort = uri.substring(7);
} else {
hostPort = uri.substring(7, optionsStartIndex);
}
// Make sure it has a host - may just be a port
int colonIndex = hostPort.indexOf(':');
if (-1 != colonIndex) {
endpoint.setHostname(hostPort.substring(0, colonIndex));
endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1)));
} else {
// No host specified - leave the default host and set the port
endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1)));
}
return endpoint;
}
}
| tkopczynski/camel | components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpComponent.java | Java | apache-2.0 | 2,487 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.sql.planner.assertions;
import com.google.common.collect.ImmutableList;
import io.trino.Session;
import io.trino.metadata.Metadata;
import io.trino.sql.parser.ParsingOptions;
import io.trino.sql.parser.SqlParser;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.plan.ApplyNode;
import io.trino.sql.planner.plan.PlanNode;
import io.trino.sql.planner.plan.ProjectNode;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.InPredicate;
import io.trino.sql.tree.SymbolReference;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.sql.ExpressionUtils.rewriteIdentifiersToSymbolReferences;
import static java.util.Objects.requireNonNull;
public class ExpressionMatcher
implements RvalueMatcher
{
private final String sql;
private final Expression expression;
public ExpressionMatcher(String expression)
{
this.sql = requireNonNull(expression, "expression is null");
this.expression = expression(expression);
}
public ExpressionMatcher(Expression expression)
{
this.expression = requireNonNull(expression, "expression is null");
this.sql = expression.toString();
}
private Expression expression(String sql)
{
SqlParser parser = new SqlParser();
return rewriteIdentifiersToSymbolReferences(parser.createExpression(sql, new ParsingOptions()));
}
public static ExpressionMatcher inPredicate(SymbolReference value, SymbolReference valueList)
{
return new ExpressionMatcher(new InPredicate(value, valueList));
}
@Override
public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases)
{
Optional<Symbol> result = Optional.empty();
ImmutableList.Builder<Expression> matchesBuilder = ImmutableList.builder();
Map<Symbol, Expression> assignments = getAssignments(node);
if (assignments == null) {
return result;
}
ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases);
for (Map.Entry<Symbol, Expression> assignment : assignments.entrySet()) {
if (verifier.process(assignment.getValue(), expression)) {
result = Optional.of(assignment.getKey());
matchesBuilder.add(assignment.getValue());
}
}
List<Expression> matches = matchesBuilder.build();
checkState(matches.size() < 2, "Ambiguous expression %s matches multiple assignments", expression,
(matches.stream().map(Expression::toString).collect(Collectors.joining(", "))));
return result;
}
private static Map<Symbol, Expression> getAssignments(PlanNode node)
{
if (node instanceof ProjectNode) {
ProjectNode projectNode = (ProjectNode) node;
return projectNode.getAssignments().getMap();
}
else if (node instanceof ApplyNode) {
ApplyNode applyNode = (ApplyNode) node;
return applyNode.getSubqueryAssignments().getMap();
}
else {
return null;
}
}
@Override
public String toString()
{
return sql;
}
}
| electrum/presto | core/trino-main/src/test/java/io/trino/sql/planner/assertions/ExpressionMatcher.java | Java | apache-2.0 | 3,920 |
// Copyright 2010 The Bazel Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.testing.junit.runner.sharding.testing;
import static com.google.common.truth.Truth.assertThat;
import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.manipulation.Filter;
/**
* Common base class for all sharding filter tests.
*/
public abstract class ShardingFilterTestCase extends TestCase {
static final List<Description> TEST_DESCRIPTIONS = createGenericTestCaseDescriptions(6);
/**
* Returns a filter of the subclass type using the given descriptions,
* shard index, and total number of shards.
*/
protected abstract ShardingFilterFactory createShardingFilterFactory();
public final void testShardingIsCompleteAndPartitioned_oneShard() {
assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 1), TEST_DESCRIPTIONS);
}
public final void testShardingIsStable_oneShard() {
assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 1), TEST_DESCRIPTIONS);
}
public final void testShardingIsCompleteAndPartitioned_moreTestsThanShards() {
assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 5), TEST_DESCRIPTIONS);
}
public final void testShardingIsStable_moreTestsThanShards() {
assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 5), TEST_DESCRIPTIONS);
}
public final void testShardingIsCompleteAndPartitioned_sameNumberOfTestsAndShards() {
assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 6), TEST_DESCRIPTIONS);
}
public final void testShardingIsStable_sameNumberOfTestsAndShards() {
assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 6), TEST_DESCRIPTIONS);
}
public final void testShardingIsCompleteAndPartitioned_moreShardsThanTests() {
assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 7), TEST_DESCRIPTIONS);
}
public final void testShardingIsStable_moreShardsThanTests() {
assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 7), TEST_DESCRIPTIONS);
}
public final void testShardingIsCompleteAndPartitioned_duplicateDescriptions() {
List<Description> descriptions = new ArrayList<>();
descriptions.addAll(createGenericTestCaseDescriptions(6));
descriptions.addAll(createGenericTestCaseDescriptions(6));
assertShardingIsCompleteAndPartitioned(createFilters(descriptions, 7), descriptions);
}
public final void testShardingIsStable_duplicateDescriptions() {
List<Description> descriptions = new ArrayList<>();
descriptions.addAll(createGenericTestCaseDescriptions(6));
descriptions.addAll(createGenericTestCaseDescriptions(6));
assertShardingIsStable(createFilters(descriptions, 7), descriptions);
}
public final void testShouldRunTestSuite() {
Description testSuiteDescription = createTestSuiteDescription();
Filter filter = createShardingFilterFactory().createFilter(TEST_DESCRIPTIONS, 0, 1);
assertThat(filter.shouldRun(testSuiteDescription)).isTrue();
}
/**
* Creates a list of generic test case descriptions.
*
* @param numDescriptions the number of generic test descriptions to add to the list.
*/
public static List<Description> createGenericTestCaseDescriptions(int numDescriptions) {
List<Description> descriptions = new ArrayList<>();
for (int i = 0; i < numDescriptions; i++) {
descriptions.add(Description.createTestDescription(Test.class, "test" + i));
}
return descriptions;
}
protected static final List<Filter> createFilters(List<Description> descriptions, int numShards,
ShardingFilterFactory factory) {
List<Filter> filters = new ArrayList<>();
for (int shardIndex = 0; shardIndex < numShards; shardIndex++) {
filters.add(factory.createFilter(descriptions, shardIndex, numShards));
}
return filters;
}
protected final List<Filter> createFilters(List<Description> descriptions, int numShards) {
return createFilters(descriptions, numShards, createShardingFilterFactory());
}
protected static void assertThrowsExceptionForUnknownDescription(Filter filter) {
try {
filter.shouldRun(Description.createTestDescription(Object.class, "unknown"));
fail("expected thrown exception");
} catch (IllegalArgumentException expected) { }
}
/**
* Simulates test sharding with the given filters and test descriptions.
*
* @param filters a list of filters, one per test shard
* @param descriptions a list of test descriptions
* @return a mapping from each filter to the descriptions of the tests that would be run
* by the shard associated with that filter.
*/
protected static Map<Filter, List<Description>> simulateTestRun(List<Filter> filters,
List<Description> descriptions) {
Map<Filter, List<Description>> descriptionsRun = new HashMap<>();
for (Filter filter : filters) {
for (Description description : descriptions) {
if (filter.shouldRun(description)) {
addDescriptionForFilterToMap(descriptionsRun, filter, description);
}
}
}
return descriptionsRun;
}
/**
* Simulates test sharding with the given filters and test descriptions, for a
* set of test descriptions that is in a different order in every test shard.
*
* @param filters a list of filters, one per test shard
* @param descriptions a list of test descriptions
* @return a mapping from each filter to the descriptions of the tests that would be run
* by the shard associated with that filter.
*/
protected static Map<Filter, List<Description>> simulateSelfRandomizingTestRun(
List<Filter> filters, List<Description> descriptions) {
if (descriptions.isEmpty()) {
return new HashMap<>();
}
Deque<Description> mutatingDescriptions = new LinkedList<>(descriptions);
Map<Filter, List<Description>> descriptionsRun = new HashMap<>();
for (Filter filter : filters) {
// rotate the queue so that each filter gets the descriptions in a different order
mutatingDescriptions.addLast(mutatingDescriptions.pollFirst());
for (Description description : descriptions) {
if (filter.shouldRun(description)) {
addDescriptionForFilterToMap(descriptionsRun, filter, description);
}
}
}
return descriptionsRun;
}
/**
* Creates a test suite description (a Description that returns true
* when {@link org.junit.runner.Description#isSuite()} is called.)
*/
protected static Description createTestSuiteDescription() {
Description testSuiteDescription = Description.createSuiteDescription("testSuite");
testSuiteDescription.addChild(Description.createSuiteDescription("testCase"));
return testSuiteDescription;
}
/**
* Tests that the sharding is complete (each test is run at least once) and
* partitioned (each test is run at most once) -- in other words, that
* each test is run exactly once. This is a requirement of all test
* sharding functions.
*/
protected static void assertShardingIsCompleteAndPartitioned(List<Filter> filters,
List<Description> descriptions) {
Map<Filter, List<Description>> run = simulateTestRun(filters, descriptions);
assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions);
run = simulateSelfRandomizingTestRun(filters, descriptions);
assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions);
}
/**
* Tests that sharding is stable for the given filters, regardless of the
* ordering of the descriptions. This is useful for verifying that sharding
* works with self-randomizing test suites, and a requirement of all test
* sharding functions.
*/
protected static void assertShardingIsStable(
List<Filter> filters, List<Description> descriptions) {
Map<Filter, List<Description>> run1 = simulateTestRun(filters, descriptions);
Map<Filter, List<Description>> run2 = simulateTestRun(filters, descriptions);
assertThat(run2).isEqualTo(run1);
Map<Filter, List<Description>> randomizedRun1 =
simulateSelfRandomizingTestRun(filters, descriptions);
Map<Filter, List<Description>> randomizedRun2 =
simulateSelfRandomizingTestRun(filters, descriptions);
assertThat(randomizedRun2).isEqualTo(randomizedRun1);
}
private static void addDescriptionForFilterToMap(
Map<Filter, List<Description>> descriptionsRun, Filter filter, Description description) {
List<Description> descriptions = descriptionsRun.get(filter);
if (descriptions == null) {
descriptions = new ArrayList<>();
descriptionsRun.put(filter, descriptions);
}
descriptions.add(description);
}
private static Collection<Description> getAllValuesInMap(Map<Filter, List<Description>> map) {
Collection<Description> allDescriptions = new ArrayList<>();
for (List<Description> descriptions : map.values()) {
allDescriptions.addAll(descriptions);
}
return allDescriptions;
}
/**
* Returns whether the Collection and the List contain exactly the same elements with the same
* frequency, ignoring the ordering.
*/
private static void assertThatCollectionContainsExactlyElementsInList(
Collection<Description> actual, List<Description> expectedDescriptions) {
String basicAssertionMessage = "Elements of collection " + actual + " are not the same as the "
+ "elements of expected list " + expectedDescriptions + ". ";
if (actual.size() != expectedDescriptions.size()) {
throw new AssertionError(basicAssertionMessage + "The number of elements is different.");
}
List<Description> actualDescriptions = new ArrayList<Description>(actual);
// Keeps track of already reviewed descriptions, so they won't be checked again when next
// encountered.
// Note: this algorithm has O(n^2) time complexity and will be slow for large inputs.
Set<Description> reviewedDescriptions = new HashSet<>();
for (int i = 0; i < actual.size(); i++) {
Description currDescription = actualDescriptions.get(i);
// If already reviewed, skip.
if (reviewedDescriptions.contains(currDescription)) {
continue;
}
int actualFreq = 0;
int expectedFreq = 0;
// Count the frequency of the current description in both lists.
for (int j = 0; j < actual.size(); j++) {
if (currDescription.equals(actualDescriptions.get(j))) {
actualFreq++;
}
if (currDescription.equals(expectedDescriptions.get(j))) {
expectedFreq++;
}
}
if (actualFreq < expectedFreq) {
throw new AssertionError(basicAssertionMessage + "There are " + (expectedFreq - actualFreq)
+ " missing occurrences of " + currDescription + ".");
} else if (actualFreq > expectedFreq) {
throw new AssertionError(basicAssertionMessage + "There are " + (actualFreq - expectedFreq)
+ " unexpected occurrences of " + currDescription + ".");
}
reviewedDescriptions.add(currDescription);
}
}
}
| damienmg/bazel | src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java | Java | apache-2.0 | 12,016 |
/*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.service;
import java.util.Objects;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ComparisonChain;
import org.onosproject.store.Timestamp;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Logical timestamp for versions.
* <p>
* The version is a logical timestamp that represents a point in logical time at which an event occurs.
* This is used in both pessimistic and optimistic locking protocols to ensure that the state of a shared resource
* has not changed at the end of a transaction.
*/
public class Version implements Timestamp {
private final long version;
public Version(long version) {
this.version = version;
}
@Override
public int compareTo(Timestamp o) {
checkArgument(o instanceof Version,
"Must be LockVersion", o);
Version that = (Version) o;
return ComparisonChain.start()
.compare(this.version, that.version)
.result();
}
@Override
public int hashCode() {
return Long.hashCode(version);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Version)) {
return false;
}
Version that = (Version) obj;
return Objects.equals(this.version, that.version);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("version", version)
.toString();
}
/**
* Returns the lock version.
*
* @return the lock version
*/
public long value() {
return this.version;
}
} | gkatsikas/onos | core/api/src/main/java/org/onosproject/store/service/Version.java | Java | apache-2.0 | 2,369 |
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.nativeplatform.internal;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.FileCollectionFactory;
import org.gradle.language.nativeplatform.DependentSourceSet;
import org.gradle.nativeplatform.*;
import org.gradle.nativeplatform.internal.resolve.NativeBinaryRequirementResolveResult;
import org.gradle.nativeplatform.internal.resolve.NativeDependencyResolver;
import org.gradle.nativeplatform.platform.NativePlatform;
import org.gradle.nativeplatform.toolchain.NativeToolChain;
import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider;
import org.gradle.nativeplatform.toolchain.internal.PreCompiledHeader;
import org.gradle.platform.base.internal.BinarySpecInternal;
import java.io.File;
import java.util.Collection;
import java.util.Map;
public interface NativeBinarySpecInternal extends NativeBinarySpec, BinarySpecInternal {
void setFlavor(Flavor flavor);
void setToolChain(NativeToolChain toolChain);
void setTargetPlatform(NativePlatform targetPlatform);
void setBuildType(BuildType buildType);
Tool getToolByName(String name);
PlatformToolProvider getPlatformToolProvider();
void setPlatformToolProvider(PlatformToolProvider toolProvider);
void setResolver(NativeDependencyResolver resolver);
void setFileCollectionFactory(FileCollectionFactory fileCollectionFactory);
File getPrimaryOutput();
Collection<NativeDependencySet> getLibs(DependentSourceSet sourceSet);
Collection<NativeLibraryBinary> getDependentBinaries();
/**
* Adds some files to include as input to the link/assemble step of this binary.
*/
void binaryInputs(FileCollection files);
Collection<NativeBinaryRequirementResolveResult> getAllResolutions();
Map<File, PreCompiledHeader> getPrefixFileToPCH();
void addPreCompiledHeaderFor(DependentSourceSet sourceSet);
}
| gstevey/gradle | subprojects/platform-native/src/main/java/org/gradle/nativeplatform/internal/NativeBinarySpecInternal.java | Java | apache-2.0 | 2,517 |
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.engine.local;
import java.util.Map;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.engine.OEngineAbstract;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.cache.local.O2QCache;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage;
/**
* @author Andrey Lomakin
* @since 28.03.13
*/
public class OEngineLocalPaginated extends OEngineAbstract {
public static final String NAME = "plocal";
private final O2QCache readCache;
public OEngineLocalPaginated() {
readCache = new O2QCache(
(long) (OGlobalConfiguration.DISK_CACHE_SIZE.getValueAsLong() * 1024 * 1024 * ((100 - OGlobalConfiguration.DISK_WRITE_CACHE_PART
.getValueAsInteger()) / 100.0)), OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, true);
try {
readCache.registerMBean();
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for read cache cannot be registered", e);
}
}
public OStorage createStorage(final String dbName, final Map<String, String> configuration) {
try {
// GET THE STORAGE
return new OLocalPaginatedStorage(dbName, dbName, getMode(configuration), generateStorageId(), readCache);
} catch (Throwable t) {
OLogManager.instance().error(this,
"Error on opening database: " + dbName + ". Current location is: " + new java.io.File(".").getAbsolutePath(), t,
ODatabaseException.class);
}
return null;
}
public String getName() {
return NAME;
}
public boolean isShared() {
return true;
}
@Override
public void shutdown() {
super.shutdown();
readCache.clear();
try {
readCache.unregisterMBean();
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for read cache cannot be unregistered", e);
}
}
}
| sanyaade-g2g-repos/orientdb | core/src/main/java/com/orientechnologies/orient/core/engine/local/OEngineLocalPaginated.java | Java | apache-2.0 | 2,893 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.common.api;
@FunctionalInterface
public interface ITreeIndexMetadataFrameFactory {
ITreeIndexMetadataFrame createFrame();
}
| ty1er/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-storage-am-common/src/main/java/org/apache/hyracks/storage/am/common/api/ITreeIndexMetadataFrameFactory.java | Java | apache-2.0 | 976 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.jdbc.test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import org.apache.calcite.rel.core.JoinRelType;
import org.apache.drill.common.logical.LogicalPlan;
import org.apache.drill.common.logical.PlanProperties;
import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.common.logical.data.Filter;
import org.apache.drill.common.logical.data.Join;
import org.apache.drill.common.logical.data.Limit;
import org.apache.drill.common.logical.data.LogicalOperator;
import org.apache.drill.common.logical.data.Order;
import org.apache.drill.common.logical.data.Project;
import org.apache.drill.common.logical.data.Scan;
import org.apache.drill.common.logical.data.Store;
import org.apache.drill.common.logical.data.Union;
import org.apache.drill.jdbc.JdbcTestBase;
import org.apache.drill.categories.JdbcTest;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.io.Resources;
import org.junit.experimental.categories.Category;
/** Unit tests for Drill's JDBC driver. */
@Ignore // ignore for now.
@Category(JdbcTest.class)
public class JdbcDataTest extends JdbcTestBase {
private static String MODEL;
private static String EXPECTED;
@BeforeClass
public static void setupFixtures() throws IOException {
MODEL = Resources.toString(Resources.getResource("test-models.json"), Charsets.UTF_8);
EXPECTED = Resources.toString(Resources.getResource("donuts-output-data.txt"), Charsets.UTF_8);
}
/**
* Command-line utility to execute a logical plan.
*
* <p>
* The forwarding method ensures that the IDE calls this method with the right classpath.
* </p>
*/
public static void main(String[] args) throws Exception {
}
/** Load driver. */
@Test
public void testLoadDriver() throws ClassNotFoundException {
Class.forName("org.apache.drill.jdbc.Driver");
}
/**
* Load the driver using ServiceLoader
*/
@Test
public void testLoadDriverServiceLoader() {
ServiceLoader<Driver> sl = ServiceLoader.load(Driver.class);
for(Iterator<Driver> it = sl.iterator(); it.hasNext(); ) {
Driver driver = it.next();
if (driver instanceof org.apache.drill.jdbc.Driver) {
return;
}
}
Assert.fail("org.apache.drill.jdbc.Driver not found using ServiceLoader");
}
/** Load driver and make a connection. */
@Test
public void testConnect() throws Exception {
Class.forName("org.apache.drill.jdbc.Driver");
final Connection connection = DriverManager.getConnection("jdbc:drill:zk=local");
connection.close();
}
/** Load driver, make a connection, prepare a statement. */
@Test
public void testPrepare() throws Exception {
withModel(MODEL, "DONUTS").withConnection(new Function<Connection, Void>() {
@Override
public Void apply(Connection connection) {
try {
final Statement statement = connection.prepareStatement("select * from donuts");
statement.close();
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
/** Simple query against JSON. */
@Test
public void testSelectJson() throws Exception {
withModel(MODEL, "DONUTS").sql("select * from donuts").returns(EXPECTED);
}
/** Simple query against EMP table in HR database. */
@Test
public void testSelectEmployees() throws Exception {
withModel(MODEL, "HR")
.sql("select * from employees")
.returns(
"_MAP={deptId=31, lastName=Rafferty}\n" + "_MAP={deptId=33, lastName=Jones}\n"
+ "_MAP={deptId=33, lastName=Steinberg}\n" + "_MAP={deptId=34, lastName=Robinson}\n"
+ "_MAP={deptId=34, lastName=Smith}\n" + "_MAP={lastName=John}\n");
}
/** Simple query against EMP table in HR database. */
@Test
public void testSelectEmpView() throws Exception {
withModel(MODEL, "HR")
.sql("select * from emp")
.returns(
"DEPTID=31; LASTNAME=Rafferty\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n"
+ "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=null; LASTNAME=John\n");
}
/** Simple query against EMP table in HR database. */
@Test
public void testSelectDept() throws Exception {
withModel(MODEL, "HR")
.sql("select * from departments")
.returns(
"_MAP={deptId=31, name=Sales}\n" + "_MAP={deptId=33, name=Engineering}\n"
+ "_MAP={deptId=34, name=Clerical}\n" + "_MAP={deptId=35, name=Marketing}\n");
}
/** Query with project list. No field references yet. */
@Test
public void testProjectConstant() throws Exception {
withModel(MODEL, "DONUTS").sql("select 1 + 3 as c from donuts")
.returns("C=4\n" + "C=4\n" + "C=4\n" + "C=4\n" + "C=4\n");
}
/** Query that projects an element from the map. */
@Test
public void testProject() throws Exception {
withModel(MODEL, "DONUTS").sql("select _MAP['ppu'] as ppu from donuts")
.returns("PPU=0.55\n" + "PPU=0.69\n" + "PPU=0.55\n" + "PPU=0.69\n" + "PPU=1.0\n");
}
/** Same logic as {@link #testProject()}, but using a subquery. */
@Test
public void testProjectOnSubquery() throws Exception {
withModel(MODEL, "DONUTS").sql("select d['ppu'] as ppu from (\n" + " select _MAP as d from donuts)")
.returns("PPU=0.55\n" + "PPU=0.69\n" + "PPU=0.55\n" + "PPU=0.69\n" + "PPU=1.0\n");
}
/** Checks the logical plan. */
@Test
public void testProjectPlan() throws Exception {
LogicalPlan plan = withModel(MODEL, "DONUTS")
.sql("select _MAP['ppu'] as ppu from donuts")
.logicalPlan();
PlanProperties planProperties = plan.getProperties();
Assert.assertEquals("optiq", planProperties.generator.type);
Assert.assertEquals("na", planProperties.generator.info);
Assert.assertEquals(1, planProperties.version);
Assert.assertEquals(PlanProperties.PlanType.APACHE_DRILL_LOGICAL, planProperties.type);
Map<String, StoragePluginConfig> seConfigs = plan.getStorageEngines();
StoragePluginConfig config = seConfigs.get("donuts-json");
// Assert.assertTrue(config != null && config instanceof ClasspathRSE.ClasspathRSEConfig);
config = seConfigs.get("queue");
// Assert.assertTrue(config != null && config instanceof QueueRSE.QueueRSEConfig);
Scan scan = findOnlyOperator(plan, Scan.class);
Assert.assertEquals("donuts-json", scan.getStorageEngine());
Project project = findOnlyOperator(plan, Project.class);
Assert.assertEquals(1, project.getSelections().size());
Assert.assertEquals(Scan.class, project.getInput().getClass());
Store store = findOnlyOperator(plan, Store.class);
Assert.assertEquals("queue", store.getStorageEngine());
Assert.assertEquals("output sink", store.getMemo());
Assert.assertEquals(Project.class, store.getInput().getClass());
}
/**
* Query with subquery, filter, and projection of one real and one nonexistent field from a map field.
*/
@Test
public void testProjectFilterSubquery() throws Exception {
withModel(MODEL, "DONUTS")
.sql(
"select d['name'] as name, d['xx'] as xx from (\n" + " select _MAP as d from donuts)\n"
+ "where cast(d['ppu'] as double) > 0.6")
.returns("NAME=Raised; XX=null\n" + "NAME=Filled; XX=null\n" + "NAME=Apple Fritter; XX=null\n");
}
private static <T extends LogicalOperator> Iterable<T> findOperator(LogicalPlan plan, final Class<T> operatorClazz) {
return (Iterable<T>) Iterables.filter(plan.getSortedOperators(), new Predicate<LogicalOperator>() {
@Override
public boolean apply(LogicalOperator input) {
return input.getClass().equals(operatorClazz);
}
});
}
private static <T extends LogicalOperator> T findOnlyOperator(LogicalPlan plan, final Class<T> operatorClazz) {
return Iterables.getOnlyElement(findOperator(plan, operatorClazz));
}
@Test
public void testProjectFilterSubqueryPlan() throws Exception {
LogicalPlan plan = withModel(MODEL, "DONUTS")
.sql(
"select d['name'] as name, d['xx'] as xx from (\n" + " select _MAP['donuts'] as d from donuts)\n"
+ "where cast(d['ppu'] as double) > 0.6")
.logicalPlan();
PlanProperties planProperties = plan.getProperties();
Assert.assertEquals("optiq", planProperties.generator.type);
Assert.assertEquals("na", planProperties.generator.info);
Assert.assertEquals(1, planProperties.version);
Assert.assertEquals(PlanProperties.PlanType.APACHE_DRILL_LOGICAL, planProperties.type);
Map<String, StoragePluginConfig> seConfigs = plan.getStorageEngines();
StoragePluginConfig config = seConfigs.get("donuts-json");
// Assert.assertTrue(config != null && config instanceof ClasspathRSE.ClasspathRSEConfig);
config = seConfigs.get("queue");
// Assert.assertTrue(config != null && config instanceof QueueRSE.QueueRSEConfig);
Scan scan = findOnlyOperator(plan, Scan.class);
Assert.assertEquals("donuts-json", scan.getStorageEngine());
Filter filter = findOnlyOperator(plan, Filter.class);
Assert.assertTrue(filter.getInput() instanceof Scan);
Project[] projects = Iterables.toArray(findOperator(plan, Project.class), Project.class);
Assert.assertEquals(2, projects.length);
Assert.assertEquals(1, projects[0].getSelections().size());
Assert.assertEquals(Filter.class, projects[0].getInput().getClass());
Assert.assertEquals(2, projects[1].getSelections().size());
Assert.assertEquals(Project.class, projects[1].getInput().getClass());
Store store = findOnlyOperator(plan, Store.class);
Assert.assertEquals("queue", store.getStorageEngine());
Assert.assertEquals("output sink", store.getMemo());
Assert.assertEquals(Project.class, store.getInput().getClass());
}
/** Query that projects one field. (Disabled; uses sugared syntax.) */
@Test @Ignore
public void testProjectNestedFieldSugared() throws Exception {
withModel(MODEL, "DONUTS").sql("select donuts.ppu from donuts")
.returns("C=4\n" + "C=4\n" + "C=4\n" + "C=4\n" + "C=4\n");
}
/** Query with filter. No field references yet. */
@Test
public void testFilterConstantFalse() throws Exception {
withModel(MODEL, "DONUTS").sql("select * from donuts where 3 > 4").returns("");
}
@Test
public void testFilterConstant() throws Exception {
withModel(MODEL, "DONUTS").sql("select * from donuts where 3 < 4").returns(EXPECTED);
}
@Ignore
@Test
public void testValues() throws Exception {
withModel(MODEL, "DONUTS").sql("values (1)").returns("EXPR$0=1\n");
// Enable when https://issues.apache.org/jira/browse/DRILL-57 fixed
// .planContains("store");
}
@Test
public void testJoin() throws Exception {
Join join = withModel(MODEL, "HR")
.sql("select * from emp join dept on emp.deptId = dept.deptId")
.returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales",
"DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering",
"DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering",
"DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical",
"DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical").planContains(Join.class);
Assert.assertEquals(JoinRelType.INNER, join.getJoinType());
}
@Test
public void testLeftJoin() throws Exception {
Join join = withModel(MODEL, "HR")
.sql("select * from emp left join dept on emp.deptId = dept.deptId")
.returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales",
"DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering",
"DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering",
"DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical",
"DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical",
"DEPTID=null; LASTNAME=John; DEPTID0=null; NAME=null").planContains(Join.class);
Assert.assertEquals(JoinRelType.LEFT, join.getJoinType());
}
/**
* Right join is tricky because Drill's "join" operator only supports "left", so we have to flip inputs.
*/
@Test @Ignore
public void testRightJoin() throws Exception {
Join join = withModel(MODEL, "HR").sql("select * from emp right join dept on emp.deptId = dept.deptId")
.returnsUnordered("xx").planContains(Join.class);
Assert.assertEquals(JoinRelType.LEFT, join.getJoinType());
}
@Test
public void testFullJoin() throws Exception {
Join join = withModel(MODEL, "HR")
.sql("select * from emp full join dept on emp.deptId = dept.deptId")
.returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales",
"DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering",
"DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering",
"DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical",
"DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical",
"DEPTID=null; LASTNAME=John; DEPTID0=null; NAME=null",
"DEPTID=null; LASTNAME=null; DEPTID0=35; NAME=Marketing").planContains(Join.class);
Assert.assertEquals(JoinRelType.FULL, join.getJoinType());
}
/**
* Join on subquery; also tests that if a field of the same name exists in both inputs, both fields make it through
* the join.
*/
@Test
public void testJoinOnSubquery() throws Exception {
Join join = withModel(MODEL, "HR")
.sql(
"select * from (\n" + "select deptId, lastname, 'x' as name from emp) as e\n"
+ " join dept on e.deptId = dept.deptId")
.returnsUnordered("DEPTID=31; LASTNAME=Rafferty; NAME=x; DEPTID0=31; NAME0=Sales",
"DEPTID=33; LASTNAME=Jones; NAME=x; DEPTID0=33; NAME0=Engineering",
"DEPTID=33; LASTNAME=Steinberg; NAME=x; DEPTID0=33; NAME0=Engineering",
"DEPTID=34; LASTNAME=Robinson; NAME=x; DEPTID0=34; NAME0=Clerical",
"DEPTID=34; LASTNAME=Smith; NAME=x; DEPTID0=34; NAME0=Clerical").planContains(Join.class);
Assert.assertEquals(JoinRelType.INNER, join.getJoinType());
}
/** Tests that one of the FoodMart tables is present. */
@Test @Ignore
public void testFoodMart() throws Exception {
withModel(MODEL, "FOODMART")
.sql("select * from product_class where cast(_map['product_class_id'] as integer) < 3")
.returnsUnordered(
"_MAP={product_category=Seafood, product_class_id=2, product_department=Seafood, product_family=Food, product_subcategory=Shellfish}",
"_MAP={product_category=Specialty, product_class_id=1, product_department=Produce, product_family=Food, product_subcategory=Nuts}");
}
@Test
public void testUnionAll() throws Exception {
Union union = withModel(MODEL, "HR")
.sql("select deptId from dept\n" + "union all\n" + "select deptId from emp")
.returnsUnordered("DEPTID=31", "DEPTID=33", "DEPTID=34", "DEPTID=35", "DEPTID=null")
.planContains(Union.class);
Assert.assertFalse(union.isDistinct());
}
@Test
public void testUnion() throws Exception {
Union union = withModel(MODEL, "HR")
.sql("select deptId from dept\n" + "union\n" + "select deptId from emp")
.returnsUnordered("DEPTID=31", "DEPTID=33", "DEPTID=34", "DEPTID=35", "DEPTID=null")
.planContains(Union.class);
Assert.assertTrue(union.isDistinct());
}
@Test
public void testOrderByDescNullsFirst() throws Exception {
// desc nulls last
withModel(MODEL, "HR")
.sql("select * from emp order by deptId desc nulls first")
.returns(
"DEPTID=null; LASTNAME=John\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n"
+ "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n")
.planContains(Order.class);
}
@Test
public void testOrderByDescNullsLast() throws Exception {
// desc nulls first
withModel(MODEL, "HR")
.sql("select * from emp order by deptId desc nulls last")
.returns(
"DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=33; LASTNAME=Jones\n"
+ "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n" + "DEPTID=null; LASTNAME=John\n")
.planContains(Order.class);
}
@Test @Ignore
public void testOrderByDesc() throws Exception {
// desc is implicitly "nulls first" (i.e. null sorted as +inf)
// Current behavior is to sort nulls last. This is wrong.
withModel(MODEL, "HR")
.sql("select * from emp order by deptId desc")
.returns(
"DEPTID=null; LASTNAME=John\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n"
+ "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n")
.planContains(Order.class);
}
@Test
public void testOrderBy() throws Exception {
// no sort order specified is implicitly "asc", and asc is "nulls last"
withModel(MODEL, "HR")
.sql("select * from emp order by deptId")
.returns(
"DEPTID=31; LASTNAME=Rafferty\n"
+ "DEPTID=33; LASTNAME=Jones\n"
+ "DEPTID=33; LASTNAME=Steinberg\n"
+ "DEPTID=34; LASTNAME=Robinson\n"
+ "DEPTID=34; LASTNAME=Smith\n"
+ "DEPTID=null; LASTNAME=John\n")
.planContains(Order.class);
}
@Test
public void testLimit() throws Exception {
withModel(MODEL, "HR")
.sql("select LASTNAME from emp limit 2")
.returns("LASTNAME=Rafferty\n" +
"LASTNAME=Jones")
.planContains(Limit.class);
}
@Test
public void testLimitOrderBy() throws Exception {
TestDataConnection tdc = withModel(MODEL, "HR")
.sql("select LASTNAME from emp order by LASTNAME limit 2")
.returns("LASTNAME=John\n" +
"LASTNAME=Jones");
tdc.planContains(Limit.class);
tdc.planContains(Order.class);
}
@Test
public void testOrderByWithOffset() throws Exception {
withModel(MODEL, "HR")
.sql("select LASTNAME from emp order by LASTNAME asc offset 3")
.returns("LASTNAME=Robinson\n" +
"LASTNAME=Smith\n" +
"LASTNAME=Steinberg")
.planContains(Limit.class);
}
@Test
public void testOrderByWithOffsetAndFetch() throws Exception {
withModel(MODEL, "HR")
.sql("select LASTNAME from emp order by LASTNAME asc offset 3 fetch next 2 rows only")
.returns("LASTNAME=Robinson\n" +
"LASTNAME=Smith")
.planContains(Limit.class);
}
}
| parthchandra/incubator-drill | exec/jdbc/src/test/java/org/apache/drill/jdbc/test/JdbcDataTest.java | Java | apache-2.0 | 19,946 |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.sabrcube;
import static com.opengamma.engine.value.ValueRequirementNames.SABR_SURFACES;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.interestrate.PresentValueCurveSensitivitySABRCalculator;
import com.opengamma.analytics.financial.interestrate.PresentValueNodeSensitivityCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateCorrelationParameters;
import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateDataBundle;
import com.opengamma.analytics.math.function.DoubleFunction1D;
import com.opengamma.analytics.math.surface.InterpolatedDoublesSurface;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.SurfaceAndCubePropertyNames;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.analytics.model.sabr.SABRDiscountingFunction;
import com.opengamma.financial.analytics.model.volatility.SmileFittingPropertyNamesAndValues;
import com.opengamma.financial.analytics.volatility.fittedresults.SABRFittedSurfaces;
import com.opengamma.financial.security.FinancialSecurityTypes;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.util.money.Currency;
/**
* @deprecated Use descendants of {@link SABRDiscountingFunction}
*/
@Deprecated
public class SABRCMSSpreadNoExtrapolationYCNSFunction extends SABRYCNSFunction {
private static final PresentValueNodeSensitivityCalculator NSC = PresentValueNodeSensitivityCalculator.using(PresentValueCurveSensitivitySABRCalculator.getInstance());
@Override
public ComputationTargetType getTargetType() {
return FinancialSecurityTypes.CAP_FLOOR_CMS_SPREAD_SECURITY;
}
@Override
protected SABRInterestRateDataBundle getModelParameters(final ComputationTarget target, final FunctionInputs inputs, final Currency currency,
final YieldCurveBundle yieldCurves, final ValueRequirement desiredValue) {
final Object surfacesObject = inputs.getValue(SABR_SURFACES);
if (surfacesObject == null) {
throw new OpenGammaRuntimeException("Could not get SABR parameter surfaces");
}
final SABRFittedSurfaces surfaces = (SABRFittedSurfaces) surfacesObject;
final InterpolatedDoublesSurface alphaSurface = surfaces.getAlphaSurface();
final InterpolatedDoublesSurface betaSurface = surfaces.getBetaSurface();
final InterpolatedDoublesSurface nuSurface = surfaces.getNuSurface();
final InterpolatedDoublesSurface rhoSurface = surfaces.getRhoSurface();
final DoubleFunction1D correlationFunction = getCorrelationFunction();
final SABRInterestRateCorrelationParameters modelParameters = new SABRInterestRateCorrelationParameters(alphaSurface, betaSurface, rhoSurface, nuSurface, correlationFunction);
return new SABRInterestRateDataBundle(modelParameters, yieldCurves);
}
@Override
protected ValueProperties.Builder createValueProperties(final Currency currency) {
return createValueProperties()
.with(ValuePropertyNames.CURRENCY, currency.getCode())
.with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode())
.withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG)
.withAny(ValuePropertyNames.CURVE)
.withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION)
.withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION)
.withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION)
.withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION)
.withAny(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD)
.with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR)
.with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION);
}
@Override
protected ValueProperties.Builder createValueProperties(final ComputationTarget target, final ValueRequirement desiredValue) {
final String cubeDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION);
final String cubeSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION);
final String surfaceDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION);
final String surfaceSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION);
final String currency = FinancialSecurityUtils.getCurrency(target.getSecurity()).getCode();
final String curveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
final String fittingMethod = desiredValue.getConstraint(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD);
final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
return createValueProperties()
.with(ValuePropertyNames.CURRENCY, currency)
.with(ValuePropertyNames.CURVE_CURRENCY, currency)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfig)
.with(ValuePropertyNames.CURVE, curveName)
.with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION, cubeDefinitionName)
.with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION, cubeSpecificationName)
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION, surfaceDefinitionName)
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION, surfaceSpecificationName)
.with(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD, fittingMethod)
.with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR)
.with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION);
}
@Override
protected PresentValueNodeSensitivityCalculator getNodeSensitivityCalculator(final ValueRequirement desiredValue) {
return NSC;
}
private static DoubleFunction1D getCorrelationFunction() {
return new DoubleFunction1D() {
@Override
public Double evaluate(final Double x) {
return 0.8;
}
};
}
}
| jeorme/OG-Platform | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/sabrcube/SABRCMSSpreadNoExtrapolationYCNSFunction.java | Java | apache-2.0 | 6,665 |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.databridge.agent.conf;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.wso2.carbon.databridge.agent.util.DataEndpointConstants;
public class DataEndpointConfiguration {
private String receiverURL;
private String authURL;
private String username;
private String password;
private GenericKeyedObjectPool transportPool;
private GenericKeyedObjectPool securedTransportPool;
private int batchSize;
private String publisherKey;
private String authKey;
private String sessionId;
private int corePoolSize;
private int maxPoolSize;
private int keepAliveTimeInPool;
public enum Protocol {
TCP, SSL;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
public DataEndpointConfiguration(String receiverURL, String authURL, String username, String password,
GenericKeyedObjectPool transportPool,
GenericKeyedObjectPool securedTransportPool,
int batchSize, int corePoolSize, int maxPoolSize, int keepAliveTimeInPool) {
this.receiverURL = receiverURL;
this.authURL = authURL;
this.username = username;
this.password = password;
this.transportPool = transportPool;
this.securedTransportPool = securedTransportPool;
this.publisherKey = this.receiverURL + DataEndpointConstants.SEPARATOR + username +
DataEndpointConstants.SEPARATOR + password;
this.authKey = this.authURL + DataEndpointConstants.SEPARATOR + username +
DataEndpointConstants.SEPARATOR + password;
this.batchSize = batchSize;
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.keepAliveTimeInPool = keepAliveTimeInPool;
}
public String getReceiverURL() {
return receiverURL;
}
public String getUsername() {
return username;
}
public String getAuthURL() {
return authURL;
}
public String getPassword() {
return password;
}
public String toString() {
return "ReceiverURL: " + receiverURL + "," +
"Authentication URL: " + authURL + "," +
"Username: " + username;
}
public String getPublisherKey() {
return publisherKey;
}
public String getAuthKey() {
return authKey;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public GenericKeyedObjectPool getTransportPool() {
return transportPool;
}
public GenericKeyedObjectPool getSecuredTransportPool() {
return securedTransportPool;
}
public int getCorePoolSize() {
return corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public int getKeepAliveTimeInPool() {
return keepAliveTimeInPool;
}
public int getBatchSize() {
return batchSize;
}
}
| keizer619/carbon-analytics-common | components/data-bridge/org.wso2.carbon.databridge.agent/src/main/java/org/wso2/carbon/databridge/agent/conf/DataEndpointConfiguration.java | Java | apache-2.0 | 3,842 |
/*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.operation.reference.doc;
import io.crate.operation.reference.doc.lucene.IntegerColumnReference;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class IntegerColumnReferenceTest extends DocLevelExpressionsTest {
@Override
protected void insertValues(IndexWriter writer) throws Exception {
for (int i = -10; i<10; i++) {
Document doc = new Document();
doc.add(new StringField("_id", Integer.toString(i), Field.Store.NO));
doc.add(new IntField(fieldName().name(), i, Field.Store.NO));
writer.addDocument(doc);
}
}
@Override
protected FieldMapper.Names fieldName() {
return new FieldMapper.Names("i");
}
@Override
protected FieldDataType fieldType() {
return new FieldDataType("int");
}
@Test
public void testFieldCacheExpression() throws Exception {
IntegerColumnReference integerColumn = new IntegerColumnReference(fieldName().name());
integerColumn.startCollect(ctx);
integerColumn.setNextReader(readerContext);
IndexSearcher searcher = new IndexSearcher(readerContext.reader());
TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), 20);
int i = -10;
for (ScoreDoc doc : topDocs.scoreDocs) {
integerColumn.setNextDocId(doc.doc);
assertThat(integerColumn.value(), is(i));
i++;
}
}
}
| gmrodrigues/crate | sql/src/test/java/io/crate/operation/reference/doc/IntegerColumnReferenceTest.java | Java | apache-2.0 | 3,042 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
******************************************************************************/
package org.apache.olingo.odata2.core.batch;
import java.util.List;
import org.apache.olingo.odata2.api.batch.BatchResponsePart;
import org.apache.olingo.odata2.api.processor.ODataResponse;
public class BatchResponsePartImpl extends BatchResponsePart {
private List<ODataResponse> responses;
private boolean isChangeSet;
@Override
public List<ODataResponse> getResponses() {
return responses;
}
@Override
public boolean isChangeSet() {
return isChangeSet;
}
public class BatchResponsePartBuilderImpl extends BatchResponsePartBuilder {
private List<ODataResponse> responses;
private boolean isChangeSet;
@Override
public BatchResponsePart build() {
BatchResponsePartImpl.this.responses = responses;
BatchResponsePartImpl.this.isChangeSet = isChangeSet;
return BatchResponsePartImpl.this;
}
@Override
public BatchResponsePartBuilder responses(final List<ODataResponse> responses) {
this.responses = responses;
return this;
}
@Override
public BatchResponsePartBuilder changeSet(final boolean isChangeSet) {
this.isChangeSet = isChangeSet;
return this;
}
}
}
| apache/olingo-odata2 | odata2-lib/odata-core/src/main/java/org/apache/olingo/odata2/core/batch/BatchResponsePartImpl.java | Java | apache-2.0 | 2,137 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.diskPerf;
import java.util.Arrays;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.LogWriter;
import org.apache.geode.internal.cache.DiskRegionHelperFactory;
import org.apache.geode.internal.cache.DiskRegionProperties;
import org.apache.geode.internal.cache.DiskRegionTestingBase;
import org.apache.geode.test.junit.categories.IntegrationTest;
/**
* Disk region Perf test for Overflow only with Sync writes. 1) Performance of get operation for
* entry in memory.
*/
@Category(IntegrationTest.class)
public class DiskRegOverflowSyncGetInMemPerfJUnitPerformanceTest extends DiskRegionTestingBase {
private static int ENTRY_SIZE = 1024;
private static int OP_COUNT = 10000;
private static int counter = 0;
private LogWriter log = null;
private DiskRegionProperties diskProps = new DiskRegionProperties();
@Override
protected final void preSetUp() throws Exception {
diskProps.setDiskDirs(dirs);
}
@Override
protected final void postSetUp() throws Exception {
diskProps.setOverFlowCapacity(100000);
region = DiskRegionHelperFactory.getSyncOverFlowOnlyRegion(cache, diskProps);
log = ds.getLogWriter();
}
@Override
protected final void postTearDown() throws Exception {
if (cache != null) {
cache.close();
}
if (ds != null) {
ds.disconnect();
}
}
@Test
public void testPopulatefor1Kbwrites() {
// RegionAttributes ra = region.getAttributes();
// final String key = "K";
final byte[] value = new byte[ENTRY_SIZE];
Arrays.fill(value, (byte) 77);
long startTime = System.currentTimeMillis();
for (int i = 0; i < OP_COUNT; i++) {
region.put("" + (i + 10000), value);
}
long endTime = System.currentTimeMillis();
System.out.println(" done with putting");
// Now get all the entries which are in memory.
long startTimeGet = System.currentTimeMillis();
for (int i = 0; i < OP_COUNT; i++) {
region.get("" + (i + 10000));
}
long endTimeGet = System.currentTimeMillis();
System.out.println(" done with getting");
region.close(); // closes disk file which will flush all buffers
float et = endTime - startTime;
float etSecs = et / 1000f;
float opPerSec = etSecs == 0 ? 0 : (OP_COUNT / (et / 1000f));
float bytesPerSec = etSecs == 0 ? 0 : ((OP_COUNT * ENTRY_SIZE) / (et / 1000f));
String stats = "et=" + et + "ms writes/sec=" + opPerSec + " bytes/sec=" + bytesPerSec;
log.info(stats);
System.out.println("Stats for 1 kb writes:" + stats);
// Perf stats for get op
float etGet = endTimeGet - startTimeGet;
float etSecsGet = etGet / 1000f;
float opPerSecGet = etSecsGet == 0 ? 0 : (OP_COUNT / (etGet / 1000f));
float bytesPerSecGet = etSecsGet == 0 ? 0 : ((OP_COUNT * ENTRY_SIZE) / (etGet / 1000f));
String statsGet = "et=" + etGet + "ms gets/sec=" + opPerSecGet + " bytes/sec=" + bytesPerSecGet;
log.info(statsGet);
System.out.println("Perf Stats of get which is in memory :" + statsGet);
}
}
| smanvi-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/cache/diskPerf/DiskRegOverflowSyncGetInMemPerfJUnitPerformanceTest.java | Java | apache-2.0 | 3,891 |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.tools.ant.taskdefs.optional;
// -- Batik classes ----------------------------------------------------------
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.apps.rasterizer.SVGConverterController;
import org.apache.batik.apps.rasterizer.SVGConverterSource;
// -- Ant classes ------------------------------------------------------------
import org.apache.tools.ant.Task;
// -- Java SDK classes -------------------------------------------------------
import java.io.File;
import java.util.Map;
import java.util.List;
/**
* Implements simple controller for the <code>SVGConverter</code> operation.
*
* <p>This is almost the same as the
* {@link org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController}
* except this produces error message when the conversion fails.</p>
*
* <p>See {@link SVGConverterController} for the method documentation.</p>
*
* @see SVGConverterController SVGConverterController
* @see org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController
*
* @author <a href="mailto:ruini@iki.fi">Henri Ruini</a>
* @version $Id: RasterizerTaskSVGConverterController.java 479617 2006-11-27 13:43:51Z dvholten $
*/
public class RasterizerTaskSVGConverterController implements SVGConverterController {
// -- Variables ----------------------------------------------------------
/** Ant task that is used to log messages. */
protected Task executingTask = null;
// -- Constructors -------------------------------------------------------
/**
* Don't allow public usage.
*/
protected RasterizerTaskSVGConverterController() {
}
/**
* Sets the given Ant task to receive log messages.
*
* @param task Ant task. The value can be <code>null</code> when log messages won't be written.
*/
public RasterizerTaskSVGConverterController(Task task) {
executingTask = task;
}
// -- Public interface ---------------------------------------------------
public boolean proceedWithComputedTask(Transcoder transcoder,
Map hints,
List sources,
List dest){
return true;
}
public boolean proceedWithSourceTranscoding(SVGConverterSource source,
File dest) {
return true;
}
public boolean proceedOnSourceTranscodingFailure(SVGConverterSource source,
File dest,
String errorCode){
if(executingTask != null) {
executingTask.log("Unable to rasterize image '"
+ source.getName() + "' to '"
+ dest.getAbsolutePath() + "': " + errorCode);
}
return true;
}
public void onSourceTranscodingSuccess(SVGConverterSource source,
File dest){
}
}
| stumoodie/PathwayEditor | libs/batik-1.7/contrib/rasterizertask/sources/org/apache/tools/ant/taskdefs/optional/RasterizerTaskSVGConverterController.java | Java | apache-2.0 | 3,878 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail;
/**
* @version $Rev$ $Date$
*/
public interface MessageAware {
public abstract MessageContext getMessageContext();
}
| salyh/geronimo-specs | geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageAware.java | Java | apache-2.0 | 952 |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.client.editors.expressions.types.function.supplementary.pmml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.soup.commons.util.Sets;
import org.kie.workbench.common.dmn.api.definition.model.Definitions;
import org.kie.workbench.common.dmn.api.definition.model.Import;
import org.kie.workbench.common.dmn.api.definition.model.ImportDMN;
import org.kie.workbench.common.dmn.api.definition.model.ImportPMML;
import org.kie.workbench.common.dmn.api.editors.included.DMNImportTypes;
import org.kie.workbench.common.dmn.api.editors.included.PMMLDocumentMetadata;
import org.kie.workbench.common.dmn.api.editors.included.PMMLIncludedModel;
import org.kie.workbench.common.dmn.api.editors.included.PMMLModelMetadata;
import org.kie.workbench.common.dmn.api.editors.included.PMMLParameterMetadata;
import org.kie.workbench.common.dmn.api.property.dmn.LocationURI;
import org.kie.workbench.common.dmn.client.editors.included.imports.IncludedModelsPageStateProviderImpl;
import org.kie.workbench.common.dmn.client.graph.DMNGraphUtils;
import org.kie.workbench.common.dmn.client.service.DMNClientServicesProxy;
import org.kie.workbench.common.stunner.core.client.service.ServiceCallback;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.uberfire.backend.vfs.Path;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyListOf;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PMMLDocumentMetadataProviderTest {
@Mock
private DMNGraphUtils graphUtils;
@Mock
private DMNClientServicesProxy clientServicesProxy;
@Mock
private IncludedModelsPageStateProviderImpl stateProvider;
@Mock
private Path dmnModelPath;
@Captor
private ArgumentCaptor<List<PMMLIncludedModel>> pmmlIncludedModelsArgumentCaptor;
@Captor
private ArgumentCaptor<ServiceCallback<List<PMMLDocumentMetadata>>> callbackArgumentCaptor;
private Definitions definitions;
private PMMLDocumentMetadataProvider provider;
@Before
public void setup() {
this.definitions = new Definitions();
this.provider = new PMMLDocumentMetadataProvider(graphUtils,
clientServicesProxy,
stateProvider);
final Diagram diagram = mock(Diagram.class);
final Metadata metadata = mock(Metadata.class);
when(stateProvider.getDiagram()).thenReturn(Optional.of(diagram));
when(diagram.getMetadata()).thenReturn(metadata);
when(metadata.getPath()).thenReturn(dmnModelPath);
when(graphUtils.getDefinitions(diagram)).thenReturn(definitions);
}
@Test
@SuppressWarnings("unchecked")
public void testLoadPMMLIncludedDocumentsDMNModelPath() {
provider.loadPMMLIncludedDocuments();
verify(clientServicesProxy).loadPMMLDocumentsFromImports(eq(dmnModelPath),
anyListOf(PMMLIncludedModel.class),
any(ServiceCallback.class));
}
@Test
@SuppressWarnings("unchecked")
public void testLoadPMMLIncludedDocumentsPMMLIncludedModels() {
final Import dmn = new ImportDMN("dmn",
new LocationURI("dmn-location"),
DMNImportTypes.DMN.getDefaultNamespace());
final Import pmml = new ImportPMML("pmml",
new LocationURI("pmml-location"),
DMNImportTypes.PMML.getDefaultNamespace());
dmn.getName().setValue("dmn");
pmml.getName().setValue("pmml");
definitions.getImport().add(dmn);
definitions.getImport().add(pmml);
provider.loadPMMLIncludedDocuments();
verify(clientServicesProxy).loadPMMLDocumentsFromImports(any(Path.class),
pmmlIncludedModelsArgumentCaptor.capture(),
any(ServiceCallback.class));
final List<PMMLIncludedModel> actualIncludedModels = pmmlIncludedModelsArgumentCaptor.getValue();
assertThat(actualIncludedModels).hasSize(1);
final PMMLIncludedModel pmmlIncludedModel = actualIncludedModels.get(0);
assertThat(pmmlIncludedModel.getModelName()).isEqualTo("pmml");
assertThat(pmmlIncludedModel.getPath()).isEqualTo("pmml-location");
assertThat(pmmlIncludedModel.getImportType()).isEqualTo(DMNImportTypes.PMML.getDefaultNamespace());
}
@Test
public void testGetPMMLDocumentNames() {
final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>();
pmmlDocuments.add(new PMMLDocumentMetadata("path1",
"zDocument1",
DMNImportTypes.PMML.getDefaultNamespace(),
Collections.emptyList()));
pmmlDocuments.add(new PMMLDocumentMetadata("path2",
"aDocument2",
DMNImportTypes.PMML.getDefaultNamespace(),
Collections.emptyList()));
final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments();
callback.onSuccess(pmmlDocuments);
final List<String> documentNames = provider.getPMMLDocumentNames();
assertThat(documentNames).containsSequence("aDocument2", "zDocument1");
}
private ServiceCallback<List<PMMLDocumentMetadata>> loadPMMLIncludedDocuments() {
provider.loadPMMLIncludedDocuments();
verify(clientServicesProxy).loadPMMLDocumentsFromImports(any(Path.class),
anyListOf(PMMLIncludedModel.class),
callbackArgumentCaptor.capture());
return callbackArgumentCaptor.getValue();
}
@Test
public void testGetPMMLDocumentModelNames() {
final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>();
pmmlDocuments.add(new PMMLDocumentMetadata("path",
"document",
DMNImportTypes.PMML.getDefaultNamespace(),
asList(new PMMLModelMetadata("zModel1",
Collections.emptySet()),
new PMMLModelMetadata("aModel2",
Collections.emptySet()))));
final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments();
callback.onSuccess(pmmlDocuments);
final List<String> modelNames = provider.getPMMLDocumentModels("document");
assertThat(modelNames).containsSequence("aModel2", "zModel1");
assertThat(provider.getPMMLDocumentModels("unknown")).isEmpty();
}
@Test
public void testGetPMMLDocumentModelParameterNames() {
final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>();
pmmlDocuments.add(new PMMLDocumentMetadata("path",
"document",
DMNImportTypes.PMML.getDefaultNamespace(),
singletonList(new PMMLModelMetadata("model",
new Sets.Builder<PMMLParameterMetadata>()
.add(new PMMLParameterMetadata("zParameter1"))
.add(new PMMLParameterMetadata("aParameter2"))
.build()))));
final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments();
callback.onSuccess(pmmlDocuments);
final List<String> modelNames = provider.getPMMLDocumentModelParameterNames("document", "model");
assertThat(modelNames).containsSequence("aParameter2", "zParameter1");
assertThat(provider.getPMMLDocumentModelParameterNames("unknown", "unknown")).isEmpty();
}
}
| mbiarnes/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/editors/expressions/types/function/supplementary/pmml/PMMLDocumentMetadataProviderTest.java | Java | apache-2.0 | 10,034 |
package com.github.dockerjava.core.command;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.github.dockerjava.api.command.ListImagesCmd;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.util.FiltersBuilder;
/**
* List images
*/
public class ListImagesCmdImpl extends AbstrDockerCmd<ListImagesCmd, List<Image>> implements ListImagesCmd {
private String imageNameFilter;
private Boolean showAll = false;
private FiltersBuilder filters = new FiltersBuilder();
public ListImagesCmdImpl(ListImagesCmd.Exec exec) {
super(exec);
}
@Override
public Map<String, List<String>> getFilters() {
return filters.build();
}
@Override
public Boolean hasShowAllEnabled() {
return showAll;
}
@Override
public ListImagesCmd withShowAll(Boolean showAll) {
this.showAll = showAll;
return this;
}
@Override
public ListImagesCmd withDanglingFilter(Boolean dangling) {
checkNotNull(dangling, "dangling have not been specified");
filters.withFilter("dangling", dangling.toString());
return this;
}
@Override
public ListImagesCmd withLabelFilter(String... labels) {
checkNotNull(labels, "labels have not been specified");
filters.withLabels(labels);
return this;
}
@Override
public ListImagesCmd withLabelFilter(Map<String, String> labels) {
checkNotNull(labels, "labels have not been specified");
filters.withLabels(labels);
return this;
}
@Override
public ListImagesCmd withImageNameFilter(String imageNameFilter) {
checkNotNull(imageNameFilter, "image name filter not specified");
this.imageNameFilter = imageNameFilter;
return this;
}
@Override
public String getImageNameFilter() {
return this.imageNameFilter;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| ollie314/docker-java | src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java | Java | apache-2.0 | 2,238 |
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.rmi.server;
/**
* An obsolete subclass of {@link ExportException}.
*
* @author Ann Wollrath
* @since JDK1.1
* @deprecated This class is obsolete. Use {@link ExportException} instead.
*/
@Deprecated
public class SocketSecurityException extends ExportException {
/* indicate compatibility with JDK 1.1.x version of class */
private static final long serialVersionUID = -7622072999407781979L;
/**
* Constructs an <code>SocketSecurityException</code> with the specified
* detail message.
*
* @param s the detail message.
* @since JDK1.1
*/
public SocketSecurityException(String s) {
super(s);
}
/**
* Constructs an <code>SocketSecurityException</code> with the specified
* detail message and nested exception.
*
* @param s the detail message.
* @param ex the nested exception
* @since JDK1.1
*/
public SocketSecurityException(String s, Exception ex) {
super(s, ex);
}
}
| shun634501730/java_source_cn | src_en/java/rmi/server/SocketSecurityException.java | Java | apache-2.0 | 1,223 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.registry.client;
import org.apache.nifi.registry.flow.VersionedFlowSnapshot;
import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata;
import java.io.IOException;
import java.util.List;
/**
* Client for interacting with snapshots.
*/
public interface FlowSnapshotClient {
/**
* Creates a new snapshot/version for the given flow.
*
* The snapshot object must have the version populated, and will receive an error if the submitted version is
* not the next one-up version.
*
* @param snapshot the new snapshot
* @return the created snapshot
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshot create(VersionedFlowSnapshot snapshot) throws NiFiRegistryException, IOException;
/**
* Gets the snapshot for the given bucket, flow, and version.
*
* @param bucketId the bucket id
* @param flowId the flow id
* @param version the version
* @return the snapshot with the given version of the given flow in the given bucket
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshot get(String bucketId, String flowId, int version) throws NiFiRegistryException, IOException;
/**
* Gets the snapshot for the given flow and version.
*
* @param flowId the flow id
* @param version the version
* @return the snapshot with the given version of the given flow
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshot get(String flowId, int version) throws NiFiRegistryException, IOException;
/**
* Gets the latest snapshot for the given flow.
*
* @param bucketId the bucket id
* @param flowId the flow id
* @return the snapshot with the latest version for the given flow
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshot getLatest(String bucketId, String flowId) throws NiFiRegistryException, IOException;
/**
* Gets the latest snapshot for the given flow.
*
* @param flowId the flow id
* @return the snapshot with the latest version for the given flow
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshot getLatest(String flowId) throws NiFiRegistryException, IOException;
/**
* Gets the latest snapshot metadata for the given flow.
*
* @param bucketId the bucket id
* @param flowId the flow id
* @return the snapshot metadata for the latest version of the given flow
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshotMetadata getLatestMetadata(String bucketId, String flowId) throws NiFiRegistryException, IOException;
/**
* Gets the latest snapshot metadata for the given flow.
*
* @param flowId the flow id
* @return the snapshot metadata for the latest version of the given flow
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
VersionedFlowSnapshotMetadata getLatestMetadata(String flowId) throws NiFiRegistryException, IOException;
/**
* Gets a list of the metadata for all snapshots of a given flow.
*
* The contents of each snapshot are not part of the response.
*
* @param bucketId the bucket id
* @param flowId the flow id
* @return the list of snapshot metadata
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
List<VersionedFlowSnapshotMetadata> getSnapshotMetadata(String bucketId, String flowId) throws NiFiRegistryException, IOException;
/**
* Gets a list of the metadata for all snapshots of a given flow.
*
* The contents of each snapshot are not part of the response.
*
* @param flowId the flow id
* @return the list of snapshot metadata
* @throws NiFiRegistryException if an error is encountered other than IOException
* @throws IOException if an I/O error is encountered
*/
List<VersionedFlowSnapshotMetadata> getSnapshotMetadata(String flowId) throws NiFiRegistryException, IOException;
}
| MikeThomsen/nifi | nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java | Java | apache-2.0 | 5,613 |
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.osc.core.broker.service.tasks.conformance.openstack;
import java.io.File;
import java.util.Set;
import javax.persistence.EntityManager;
import org.osc.core.broker.job.lock.LockObjectReference;
import org.osc.core.broker.model.entities.appliance.ApplianceSoftwareVersion;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.virtualization.openstack.OsImageReference;
import org.osc.core.broker.rest.client.openstack.openstack4j.Endpoint;
import org.osc.core.broker.rest.client.openstack.openstack4j.Openstack4jGlance;
import org.osc.core.broker.service.appliance.UploadConfig;
import org.osc.core.broker.service.persistence.OSCEntityManager;
import org.osc.core.broker.service.tasks.TransactionalTask;
import org.slf4j.LoggerFactory;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.slf4j.Logger;
@Component(service = UploadImageToGlanceTask.class,
configurationPid = "org.osc.core.broker.upload",
configurationPolicy = ConfigurationPolicy.REQUIRE)
public class UploadImageToGlanceTask extends TransactionalTask {
private final Logger log = LoggerFactory.getLogger(UploadImageToGlanceTask.class);
private String region;
private VirtualSystem vs;
private String glanceImageName;
private ApplianceSoftwareVersion applianceSoftwareVersion;
private Endpoint osEndPoint;
private String uploadPath;
@Activate
void activate(UploadConfig config) {
this.uploadPath = config.upload_path();
}
public UploadImageToGlanceTask create(VirtualSystem vs, String region, String glanceImageName, ApplianceSoftwareVersion applianceSoftwareVersion, Endpoint osEndPoint) {
UploadImageToGlanceTask task = new UploadImageToGlanceTask();
task.vs = vs;
task.region = region;
task.applianceSoftwareVersion = applianceSoftwareVersion;
task.osEndPoint = osEndPoint;
task.glanceImageName = glanceImageName;
task.name = task.getName();
task.uploadPath = this.uploadPath;
task.dbConnectionManager = this.dbConnectionManager;
task.txBroadcastUtil = this.txBroadcastUtil;
return task;
}
@Override
public void executeTransaction(EntityManager em) throws Exception {
OSCEntityManager<VirtualSystem> emgr = new OSCEntityManager<>(VirtualSystem.class, em, this.txBroadcastUtil);
this.vs = emgr.findByPrimaryKey(this.vs.getId());
this.log.info("Uploading image " + this.glanceImageName + " to region + " + this.region);
File imageFile = new File(this.uploadPath + this.applianceSoftwareVersion.getImageUrl());
try (Openstack4jGlance glance = new Openstack4jGlance(this.osEndPoint)) {
String imageId = glance.uploadImage(this.region, this.glanceImageName, imageFile, this.applianceSoftwareVersion.getImageProperties());
this.vs.addOsImageReference(new OsImageReference(this.vs, this.region, imageId));
}
OSCEntityManager.update(em, this.vs, this.txBroadcastUtil);
}
@Override
public String getName() {
return String.format("Uploading image '%s' to region '%s'", this.glanceImageName, this.region);
}
@Override
public Set<LockObjectReference> getObjects() {
return LockObjectReference.getObjectReferences(this.vs);
}
}
| emanoelxavier/osc-core | osc-server/src/main/java/org/osc/core/broker/service/tasks/conformance/openstack/UploadImageToGlanceTask.java | Java | apache-2.0 | 4,272 |
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.driver.extensions;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import org.junit.Test;
import com.google.common.testing.EqualsTester;
/**
* Unit tests for NiciraTunGpeNp class.
*/
public class NiciraTunGpeNpTest {
final byte np1 = (byte) 1;
final byte np2 = (byte) 2;
/**
* Checks the operation of equals() methods.
*/
@Test
public void testEquals() {
final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1);
final NiciraTunGpeNp sameAsTunGpeNp1 = new NiciraTunGpeNp(np1);
final NiciraTunGpeNp tunGpeNp2 = new NiciraTunGpeNp(np2);
new EqualsTester().addEqualityGroup(tunGpeNp1, sameAsTunGpeNp1).addEqualityGroup(tunGpeNp2)
.testEquals();
}
/**
* Checks the construction of a NiciraTunGpeNp object.
*/
@Test
public void testConstruction() {
final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1);
assertThat(tunGpeNp1, is(notNullValue()));
assertThat(tunGpeNp1.tunGpeNp(), is(np1));
}
}
| gkatsikas/onos | drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraTunGpeNpTest.java | Java | apache-2.0 | 1,762 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.navigation;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator;
import com.intellij.codeInsight.generation.actions.PresentableCodeInsightActionHandler;
import com.intellij.codeInsight.navigation.actions.GotoSuperAction;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.MethodCellRenderer;
import com.intellij.ide.util.PsiNavigationSupport;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.impl.FindSuperElementsHelper;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
public class JavaGotoSuperHandler implements PresentableCodeInsightActionHandler {
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID);
int offset = editor.getCaretModel().getOffset();
PsiElement[] superElements = findSuperElements(file, offset);
if (superElements.length == 0) return;
if (superElements.length == 1) {
PsiElement superElement = superElements[0].getNavigationElement();
final PsiFile containingFile = superElement.getContainingFile();
if (containingFile == null) return;
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return;
Navigatable descriptor =
PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, superElement.getTextOffset());
descriptor.navigate(true);
}
else if (superElements[0] instanceof PsiMethod) {
boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature((PsiMethod[])superElements);
PsiElementListNavigator.openTargets(editor, (PsiMethod[])superElements,
CodeInsightBundle.message("goto.super.method.chooser.title"),
CodeInsightBundle
.message("goto.super.method.findUsages.title", ((PsiMethod)superElements[0]).getName()),
new MethodCellRenderer(showMethodNames));
}
else {
NavigationUtil.getPsiElementPopup(superElements, CodeInsightBundle.message("goto.super.class.chooser.title"))
.showInBestPositionFor(editor);
}
}
@NotNull
private PsiElement[] findSuperElements(@NotNull PsiFile file, int offset) {
PsiElement element = getElement(file, offset);
if (element == null) return PsiElement.EMPTY_ARRAY;
final PsiElement psiElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class);
if (psiElement instanceof PsiFunctionalExpression) {
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(psiElement);
if (interfaceMethod != null) {
return ArrayUtil.prepend(interfaceMethod, interfaceMethod.findSuperMethods(false));
}
}
final PsiNameIdentifierOwner parent = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class, PsiClass.class);
if (parent == null) {
return PsiElement.EMPTY_ARRAY;
}
return FindSuperElementsHelper.findSuperElements(parent);
}
protected PsiElement getElement(@NotNull PsiFile file, int offset) {
return file.findElementAt(offset);
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void update(@NotNull Editor editor, @NotNull PsiFile file, Presentation presentation) {
final PsiElement element = getElement(file, editor.getCaretModel().getOffset());
final PsiElement containingElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class);
if (containingElement instanceof PsiClass) {
presentation.setText(ActionsBundle.actionText("GotoSuperClass"));
presentation.setDescription(ActionsBundle.actionDescription("GotoSuperClass"));
}
else {
presentation.setText(ActionsBundle.actionText("GotoSuperMethod"));
presentation.setDescription(ActionsBundle.actionDescription("GotoSuperMethod"));
}
}
}
| goodwinnk/intellij-community | java/java-impl/src/com/intellij/codeInsight/navigation/JavaGotoSuperHandler.java | Java | apache-2.0 | 5,139 |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.eclipse.gmf.esb.CloneTargetContainer;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow;
/**
* @generated
*/
public class MediatorFlow11CreateCommand extends EditElementCommand {
/**
* @generated
*/
public MediatorFlow11CreateCommand(CreateElementRequest req) {
super(req.getLabel(), null, req);
}
/**
* FIXME: replace with setElementToEdit()
* @generated
*/
protected EObject getElementToEdit() {
EObject container = ((CreateElementRequest) getRequest()).getContainer();
if (container instanceof View) {
container = ((View) container).getElement();
}
return container;
}
/**
* @generated
*/
public boolean canExecute() {
CloneTargetContainer container = (CloneTargetContainer) getElementToEdit();
if (container.getMediatorFlow() != null) {
return false;
}
return true;
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
MediatorFlow newElement = EsbFactory.eINSTANCE.createMediatorFlow();
CloneTargetContainer owner = (CloneTargetContainer) getElementToEdit();
owner.setMediatorFlow(newElement);
doConfigure(newElement, monitor, info);
((CreateElementRequest) getRequest()).setNewElement(newElement);
return CommandResult.newOKCommandResult(newElement);
}
/**
* @generated
*/
protected void doConfigure(MediatorFlow newElement, IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IElementType elementType = ((CreateElementRequest) getRequest()).getElementType();
ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement,
elementType);
configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext());
configureRequest.addParameters(getRequest().getParameters());
ICommand configureCommand = elementType.getEditCommand(configureRequest);
if (configureCommand != null && configureCommand.canExecute()) {
configureCommand.execute(monitor, info);
}
}
}
| chanakaudaya/developer-studio | esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/MediatorFlow11CreateCommand.java | Java | apache-2.0 | 2,841 |
package brooklyn.location.jclouds.pool;
import java.util.Map;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Processor;
import org.jclouds.domain.Location;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Throwables;
public class MachinePoolPredicates {
private static final Logger log = LoggerFactory.getLogger(MachinePoolPredicates.class);
public static Predicate<NodeMetadata> except(final MachineSet removedItems) {
return new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
return !removedItems.contains(input);
}
};
}
public static Predicate<NodeMetadata> except(final Predicate<NodeMetadata> predicateToExclude) {
return Predicates.not(predicateToExclude);
}
public static Predicate<NodeMetadata> matching(final ReusableMachineTemplate template) {
return new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
return matches(template, input);
}
};
}
public static Predicate<NodeMetadata> withTag(final String tag) {
return new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
return input.getTags().contains(tag);
}
};
}
public static Predicate<NodeMetadata> compose(final Predicate<NodeMetadata> ...predicates) {
return Predicates.and(predicates);
}
/** True iff the node matches the criteria specified in this template.
* <p>
* NB: This only checks some of the most common fields,
* plus a hashcode (in strict mode).
* In strict mode you're practically guaranteed to match only machines created by this template.
* (Add a tag(uid) and you _will_ be guaranteed, strict mode or not.)
* <p>
* Outside strict mode, some things (OS and hypervisor) can fall through the gaps.
* But if that is a problem we can easily add them in.
* <p>
* (Caveat: If explicit Hardware, Image, and/or Template were specified in the template,
* then the hash code probably will not detect it.)
**/
public static boolean matches(ReusableMachineTemplate template, NodeMetadata m) {
try {
// tags and user metadata
if (! m.getTags().containsAll( template.getTags(false) )) return false;
if (! isSubMapOf(template.getUserMetadata(false), m.getUserMetadata())) return false;
// common hardware parameters
if (template.getMinRam()!=null && m.getHardware().getRam() < template.getMinRam()) return false;
if (template.getMinCores()!=null) {
double numCores = 0;
for (Processor p: m.getHardware().getProcessors()) numCores += p.getCores();
if (numCores+0.001 < template.getMinCores()) return false;
}
if (template.getIs64bit()!=null) {
if (m.getOperatingSystem().is64Bit() != template.getIs64bit()) return false;
}
if (template.getOsFamily()!=null) {
if (m.getOperatingSystem() == null ||
!template.getOsFamily().equals(m.getOperatingSystem().getFamily())) return false;
}
if (template.getOsNameMatchesRegex()!=null) {
if (m.getOperatingSystem() == null || m.getOperatingSystem().getName()==null ||
!m.getOperatingSystem().getName().matches(template.getOsNameMatchesRegex())) return false;
}
if (template.getLocationId()!=null) {
if (!isLocationContainedIn(m.getLocation(), template.getLocationId())) return false;
}
// TODO other TemplateBuilder fields and TemplateOptions
return true;
} catch (Exception e) {
log.warn("Error (rethrowing) trying to match "+m+" against "+template+": "+e, e);
throw Throwables.propagate(e);
}
}
private static boolean isLocationContainedIn(Location location, String locationId) {
if (location==null) return false;
if (locationId.equals(location.getId())) return true;
return isLocationContainedIn(location.getParent(), locationId);
}
public static boolean isSubMapOf(Map<String, String> sub, Map<String, String> bigger) {
for (Map.Entry<String, String> e: sub.entrySet()) {
if (e.getValue()==null) {
if (!bigger.containsKey(e.getKey())) return false;
if (bigger.get(e.getKey())!=null) return false;
} else {
if (!e.getValue().equals(bigger.get(e.getKey()))) return false;
}
}
return true;
}
}
| bmwshop/brooklyn | locations/jclouds/src/main/java/brooklyn/location/jclouds/pool/MachinePoolPredicates.java | Java | apache-2.0 | 5,001 |
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.documentum.fc.client;
/** Stub interface to allow the connector to build fully.
*/
public class DfIdentityException extends DfServiceException
{
}
| kishorejangid/manifoldcf | connectors/documentum/build-stub/src/main/java/com/documentum/fc/client/DfIdentityException.java | Java | apache-2.0 | 954 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.server;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import io.airlift.configuration.Config;
import io.airlift.resolver.ArtifactResolver;
import javax.validation.constraints.NotNull;
import java.util.List;
public class DevelopmentLoaderConfig
{
private static final Splitter SPLITTER = Splitter.on(',').omitEmptyStrings().trimResults();
private List<String> plugins = ImmutableList.of();
private String mavenLocalRepository = ArtifactResolver.USER_LOCAL_REPO;
private List<String> mavenRemoteRepository = ImmutableList.of(ArtifactResolver.MAVEN_CENTRAL_URI);
public List<String> getPlugins()
{
return plugins;
}
public DevelopmentLoaderConfig setPlugins(List<String> plugins)
{
this.plugins = ImmutableList.copyOf(plugins);
return this;
}
@Config("plugin.bundles")
public DevelopmentLoaderConfig setPlugins(String plugins)
{
this.plugins = SPLITTER.splitToList(plugins);
return this;
}
@NotNull
public String getMavenLocalRepository()
{
return mavenLocalRepository;
}
@Config("maven.repo.local")
public DevelopmentLoaderConfig setMavenLocalRepository(String mavenLocalRepository)
{
this.mavenLocalRepository = mavenLocalRepository;
return this;
}
@NotNull
public List<String> getMavenRemoteRepository()
{
return mavenRemoteRepository;
}
public DevelopmentLoaderConfig setMavenRemoteRepository(List<String> mavenRemoteRepository)
{
this.mavenRemoteRepository = mavenRemoteRepository;
return this;
}
@Config("maven.repo.remote")
public DevelopmentLoaderConfig setMavenRemoteRepository(String mavenRemoteRepository)
{
this.mavenRemoteRepository = ImmutableList.copyOf(Splitter.on(',').omitEmptyStrings().trimResults().split(mavenRemoteRepository));
return this;
}
}
| electrum/presto | testing/trino-server-dev/src/main/java/io/trino/server/DevelopmentLoaderConfig.java | Java | apache-2.0 | 2,534 |
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.portlets.statistics;
import java.util.Collections;
import java.util.List;
import org.jasig.portal.events.aggr.portletlayout.PortletLayoutAggregation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import com.google.visualization.datasource.base.TypeMismatchException;
import com.google.visualization.datasource.datatable.value.NumberValue;
import com.google.visualization.datasource.datatable.value.Value;
/**
* @author Chris Waymire <cwaymire@unicon.net>
*/
@Controller
@RequestMapping(value="VIEW")
public class PortletMoveStatisticsController extends BasePortletLayoutStatisticsController<PortletMoveReportForm> {
private static final String DATA_TABLE_RESOURCE_ID = "portletMoveData";
private static final String REPORT_NAME = "portletMove.totals";
@RenderMapping(value="MAXIMIZED", params="report=" + REPORT_NAME)
public String getLoginView() throws TypeMismatchException {
return super.getLoginView();
}
@ResourceMapping(DATA_TABLE_RESOURCE_ID)
public ModelAndView renderPortletAddAggregationReport(PortletMoveReportForm form) throws TypeMismatchException {
return super.renderPortletAddAggregationReport(form);
}
@Override
public String getReportName() {
return REPORT_NAME;
}
@Override
public String getReportDataResourceId() {
return DATA_TABLE_RESOURCE_ID;
}
@Override
protected List<Value> createRowValues(PortletLayoutAggregation aggr, PortletMoveReportForm form) {
int count = aggr != null ? aggr.getMoveCount() : 0;
return Collections.<Value>singletonList(new NumberValue(count));
}
} | pspaude/uPortal | uportal-war/src/main/java/org/jasig/portal/portlets/statistics/PortletMoveStatisticsController.java | Java | apache-2.0 | 2,682 |
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.entitySystem.prefab.internal;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.terasology.assets.AssetType;
import org.terasology.assets.ResourceUrn;
import org.terasology.entitySystem.Component;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.entitySystem.prefab.PrefabData;
import java.util.List;
import java.util.Map;
/**
* @author Immortius
*/
public class PojoPrefab extends Prefab {
private Prefab parent;
private Map<Class<? extends Component>, Component> componentMap;
private List<Prefab> children = Lists.newArrayList();
private boolean persisted;
private boolean alwaysRelevant = true;
public PojoPrefab(ResourceUrn urn, AssetType<?, PrefabData> assetType, PrefabData data) {
super(urn, assetType);
reload(data);
}
@Override
public Prefab getParent() {
return parent;
}
@Override
public List<Prefab> getChildren() {
return ImmutableList.copyOf(children);
}
@Override
public boolean isPersisted() {
return persisted;
}
@Override
public boolean isAlwaysRelevant() {
return alwaysRelevant;
}
@Override
public boolean exists() {
return true;
}
@Override
public boolean hasComponent(Class<? extends Component> component) {
return componentMap.containsKey(component);
}
@Override
public <T extends Component> T getComponent(Class<T> componentClass) {
return componentClass.cast(componentMap.get(componentClass));
}
@Override
public Iterable<Component> iterateComponents() {
return ImmutableList.copyOf(componentMap.values());
}
@Override
protected void doDispose() {
}
@Override
protected void doReload(PrefabData data) {
this.componentMap = ImmutableMap.copyOf(data.getComponents());
this.persisted = data.isPersisted();
this.alwaysRelevant = data.isAlwaysRelevant();
this.parent = data.getParent();
if (parent != null && parent instanceof PojoPrefab) {
((PojoPrefab) parent).children.add(this);
}
}
}
| immortius/Terasology | engine/src/main/java/org/terasology/entitySystem/prefab/internal/PojoPrefab.java | Java | apache-2.0 | 2,855 |
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.services.jmx;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.RegisteredServiceImpl;
import org.jasig.cas.services.ServicesManager;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.util.Assert;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* Abstract base class to support both the {@link org.jasig.cas.services.ServicesManager} and the
* {@link org.jasig.cas.services.ReloadableServicesManager}.
*
* @author <a href="mailto:tobias.trelle@proximity.de">Tobias Trelle</a>
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.4.4
*/
public abstract class AbstractServicesManagerMBean<T extends ServicesManager> {
@NotNull
private T servicesManager;
protected AbstractServicesManagerMBean(final T servicesManager) {
this.servicesManager = servicesManager;
}
protected final T getServicesManager() {
return this.servicesManager;
}
@ManagedAttribute(description = "Retrieves the list of Registered Services in a slightly friendlier output.")
public final List<String> getRegisteredServicesAsStrings() {
final List<String> services = new ArrayList<String>();
for (final RegisteredService r : this.servicesManager.getAllServices()) {
services.add(new StringBuilder().append("id: ").append(r.getId())
.append(" name: ").append(r.getName())
.append(" enabled: ").append(r.isEnabled())
.append(" ssoEnabled: ").append(r.isSsoEnabled())
.append(" serviceId: ").append(r.getServiceId())
.toString());
}
return services;
}
@ManagedOperation(description = "Can remove a service based on its identifier.")
@ManagedOperationParameter(name="id", description = "the identifier to remove")
public final RegisteredService removeService(final long id) {
return this.servicesManager.delete(id);
}
@ManagedOperation(description = "Disable a service by id.")
@ManagedOperationParameter(name="id", description = "the identifier to disable")
public final void disableService(final long id) {
changeEnabledState(id, false);
}
@ManagedOperation(description = "Enable a service by its id.")
@ManagedOperationParameter(name="id", description = "the identifier to enable.")
public final void enableService(final long id) {
changeEnabledState(id, true);
}
private void changeEnabledState(final long id, final boolean newState) {
final RegisteredService r = this.servicesManager.findServiceBy(id);
Assert.notNull(r, "invalid RegisteredService id");
// we screwed up our APIs in older versions of CAS, so we need to CAST this to do anything useful.
((RegisteredServiceImpl) r).setEnabled(newState);
this.servicesManager.save(r);
}
}
| briandwyer/cas-hudson | cas-server-core/src/main/java/org/jasig/cas/services/jmx/AbstractServicesManagerMBean.java | Java | apache-2.0 | 3,919 |
/*
* Copyright (c) 2002-2015, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jline.internal;
import java.util.ArrayList;
import java.util.List;
import static jline.internal.Preconditions.checkNotNull;
/**
* Manages the JLine shutdown-hook thread and tasks to execute on shutdown.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @since 2.7
*/
public class ShutdownHooks
{
public static final String JLINE_SHUTDOWNHOOK = "jline.shutdownhook";
private static final boolean enabled = Configuration.getBoolean(JLINE_SHUTDOWNHOOK, true);
private static final List<Task> tasks = new ArrayList<Task>();
private static Thread hook;
public static synchronized <T extends Task> T add(final T task) {
checkNotNull(task);
// If not enabled ignore
if (!enabled) {
Log.debug("Shutdown-hook is disabled; not installing: ", task);
return task;
}
// Install the hook thread if needed
if (hook == null) {
hook = addHook(new Thread("JLine Shutdown Hook")
{
@Override
public void run() {
runTasks();
}
});
}
// Track the task
Log.debug("Adding shutdown-hook task: ", task);
tasks.add(task);
return task;
}
private static synchronized void runTasks() {
Log.debug("Running all shutdown-hook tasks");
// Iterate through copy of tasks list
for (Task task : tasks.toArray(new Task[tasks.size()])) {
Log.debug("Running task: ", task);
try {
task.run();
}
catch (Throwable e) {
Log.warn("Task failed", e);
}
}
tasks.clear();
}
private static Thread addHook(final Thread thread) {
Log.debug("Registering shutdown-hook: ", thread);
try {
Runtime.getRuntime().addShutdownHook(thread);
}
catch (AbstractMethodError e) {
// JDK 1.3+ only method. Bummer.
Log.debug("Failed to register shutdown-hook", e);
}
return thread;
}
public static synchronized void remove(final Task task) {
checkNotNull(task);
// ignore if not enabled or hook never installed
if (!enabled || hook == null) {
return;
}
// Drop the task
tasks.remove(task);
// If there are no more tasks, then remove the hook thread
if (tasks.isEmpty()) {
removeHook(hook);
hook = null;
}
}
private static void removeHook(final Thread thread) {
Log.debug("Removing shutdown-hook: ", thread);
try {
Runtime.getRuntime().removeShutdownHook(thread);
}
catch (AbstractMethodError e) {
// JDK 1.3+ only method. Bummer.
Log.debug("Failed to remove shutdown-hook", e);
}
catch (IllegalStateException e) {
// The VM is shutting down, not a big deal; ignore
}
}
/**
* Essentially a {@link Runnable} which allows running to throw an exception.
*/
public static interface Task
{
void run() throws Exception;
}
} | kaulkie/jline2 | src/main/java/jline/internal/ShutdownHooks.java | Java | bsd-3-clause | 3,503 |
package org.knowm.xchange.dsx.dto.trade;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
import org.knowm.xchange.dsx.dto.DSXReturn;
/** @author Mikhail Wall */
public class DSXOrderHistoryReturn extends DSXReturn<Map<Long, DSXOrderHistoryResult>> {
public DSXOrderHistoryReturn(
@JsonProperty("success") boolean success,
@JsonProperty("return") Map<Long, DSXOrderHistoryResult> value,
@JsonProperty("error") String error) {
super(success, value, error);
}
}
| chrisrico/XChange | xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/trade/DSXOrderHistoryReturn.java | Java | mit | 517 |
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.CENTURIES;
import static java.time.temporal.ChronoUnit.DECADES;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.MILLENNIA;
import static java.time.temporal.ChronoUnit.YEARS;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
/**
* A year in the ISO-8601 calendar system, such as {@code 2007}.
* <p>
* {@code Year} is an immutable date-time object that represents a year.
* Any field that can be derived from a year can be obtained.
* <p>
* <b>Note that years in the ISO chronology only align with years in the
* Gregorian-Julian system for modern years. Parts of Russia did not switch to the
* modern Gregorian/ISO rules until 1920.
* As such, historical years must be treated with caution.</b>
* <p>
* This class does not store or represent a month, day, time or time-zone.
* For example, the value "2007" can be stored in a {@code Year}.
* <p>
* Years represented by this class follow the ISO-8601 standard and use
* the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
* <p>
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which today's rules for leap years are applied for all time.
* For most applications written today, the ISO-8601 rules are entirely suitable.
* However, any application that makes use of historical dates, and requires them
* to be accurate will find the ISO-8601 approach unsuitable.
*
* <p>
* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Year} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class Year
implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {
/**
* The minimum supported year, '-999,999,999'.
*/
public static final int MIN_VALUE = -999_999_999;
/**
* The maximum supported year, '+999,999,999'.
*/
public static final int MAX_VALUE = 999_999_999;
/**
* Serialization version.
*/
private static final long serialVersionUID = -23038383694477807L;
/**
* Parser.
*/
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.toFormatter();
/**
* The year being represented.
*/
private final int year;
//-----------------------------------------------------------------------
/**
* Obtains the current year from the system clock in the default time-zone.
* <p>
* This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current year using the system clock and default time-zone, not null
*/
public static Year now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current year from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current year using the system clock, not null
*/
public static Year now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current year from the specified clock.
* <p>
* This will query the specified clock to obtain the current year.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current year, not null
*/
public static Year now(Clock clock) {
final LocalDate now = LocalDate.now(clock); // called once
return Year.of(now.getYear());
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year}.
* <p>
* This method accepts a year value from the proleptic ISO calendar system.
* <p>
* The year 2AD/CE is represented by 2.<br>
* The year 1AD/CE is represented by 1.<br>
* The year 1BC/BCE is represented by 0.<br>
* The year 2BC/BCE is represented by -1.<br>
*
* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
* @return the year, not null
* @throws DateTimeException if the field is invalid
*/
public static Year of(int isoYear) {
YEAR.checkValidValue(isoYear);
return new Year(isoYear);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a temporal object.
* <p>
* This obtains a year based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code Year}.
* <p>
* The conversion extracts the {@link ChronoField#YEAR year} field.
* The extraction is only permitted if the temporal object has an ISO
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used in queries via method reference, {@code Year::from}.
*
* @param temporal the temporal object to convert, not null
* @return the year, not null
* @throws DateTimeException if unable to convert to a {@code Year}
*/
public static Year from(TemporalAccessor temporal) {
if (temporal instanceof Year) {
return (Year) temporal;
}
Objects.requireNonNull(temporal, "temporal");
try {
if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
temporal = LocalDate.from(temporal);
}
return of(temporal.get(YEAR));
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a text string such as {@code 2007}.
* <p>
* The string must represent a valid year.
* Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
*
* @param text the text to parse such as "2007", not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text) {
return parse(text, PARSER);
}
/**
* Obtains an instance of {@code Year} from a text string using a specific formatter.
* <p>
* The text is parsed using the formatter, returning a year.
*
* @param text the text to parse, not null
* @param formatter the formatter to use, not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, Year::from);
}
//-------------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @param year the year to check
* @return true if the year is leap, false otherwise
*/
public static boolean isLeap(long year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
//-----------------------------------------------------------------------
/**
* Constructor.
*
* @param year the year to represent
*/
private Year(int year) {
this.year = year;
}
//-----------------------------------------------------------------------
/**
* Gets the year value.
* <p>
* The year returned by this method is proleptic as per {@code get(YEAR)}.
*
* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
*/
public int getValue() {
return year;
}
//-----------------------------------------------------------------------
/**
* Checks if the specified field is supported.
* <p>
* This checks if this year can be queried for the specified field.
* If false, then calling the {@link #range(TemporalField) range},
* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
* methods will throw an exception.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The supported fields are:
* <ul>
* <li>{@code YEAR_OF_ERA}
* <li>{@code YEAR}
* <li>{@code ERA}
* </ul>
* All other {@code ChronoField} instances will return false.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the field is supported is determined by the field.
*
* @param field the field to check, null returns false
* @return true if the field is supported on this year, false if not
*/
@Override
public boolean isSupported(TemporalField field) {
if (field instanceof ChronoField) {
return field == YEAR || field == YEAR_OF_ERA || field == ERA;
}
return field != null && field.isSupportedBy(this);
}
/**
* Checks if the specified unit is supported.
* <p>
* This checks if the specified unit can be added to, or subtracted from, this date-time.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
* If the unit is a {@link ChronoUnit} then the query is implemented here.
* The supported units are:
* <ul>
* <li>{@code YEARS}
* <li>{@code DECADES}
* <li>{@code CENTURIES}
* <li>{@code MILLENNIA}
* <li>{@code ERAS}
* </ul>
* All other {@code ChronoUnit} instances will return false.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
* passing {@code this} as the argument.
* Whether the unit is supported is determined by the unit.
*
* @param unit the unit to check, null returns false
* @return true if the unit can be added/subtracted, false if not
*/
@Override
public boolean isSupported(TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
}
return unit != null && unit.isSupportedBy(this);
}
//-----------------------------------------------------------------------
/**
* Gets the range of valid values for the specified field.
* <p>
* The range object expresses the minimum and maximum valid values for a field.
* This year is used to enhance the accuracy of the returned range.
* If it is not possible to return the range, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return
* appropriate range instances.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the range can be obtained is determined by the field.
*
* @param field the field to query the range for, not null
* @return the range of valid values for the field, not null
* @throws DateTimeException if the range for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
*/
@Override
public ValueRange range(TemporalField field) {
if (field == YEAR_OF_ERA) {
return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));
}
return Temporal.super.range(field);
}
/**
* Gets the value of the specified field from this year as an {@code int}.
* <p>
* This queries this year for the value for the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained or
* the value is outside the range of valid values for the field
* @throws UnsupportedTemporalTypeException if the field is not supported or
* the range of values exceeds an {@code int}
* @throws ArithmeticException if numeric overflow occurs
*/
@Override // override for Javadoc
public int get(TemporalField field) {
return range(field).checkValidIntValue(getLong(field), field);
}
/**
* Gets the value of the specified field from this year as a {@code long}.
* <p>
* This queries this year for the value for the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
case YEAR: return year;
case ERA: return (year < 1 ? 0 : 1);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
//-----------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @return true if the year is leap, false otherwise
*/
public boolean isLeap() {
return Year.isLeap(year);
}
/**
* Checks if the month-day is valid for this year.
* <p>
* This method checks whether this year and the input month and day form
* a valid date.
*
* @param monthDay the month-day to validate, null returns false
* @return true if the month and day are valid for this year
*/
public boolean isValidMonthDay(MonthDay monthDay) {
return monthDay != null && monthDay.isValidYear(year);
}
/**
* Gets the length of this year in days.
*
* @return the length of this year in days, 365 or 366
*/
public int length() {
return isLeap() ? 366 : 365;
}
//-----------------------------------------------------------------------
/**
* Returns an adjusted copy of this year.
* <p>
* This returns a {@code Year}, based on this one, with the year adjusted.
* The adjustment takes place using the specified adjuster strategy object.
* Read the documentation of the adjuster to understand what adjustment will be made.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalAdjuster#adjustInto(Temporal)} method on the
* specified adjuster passing {@code this} as the argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param adjuster the adjuster to use, not null
* @return a {@code Year} based on {@code this} with the adjustment made, not null
* @throws DateTimeException if the adjustment cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalAdjuster adjuster) {
return (Year) adjuster.adjustInto(this);
}
/**
* Returns a copy of this year with the specified field set to a new value.
* <p>
* This returns a {@code Year}, based on this one, with the value
* for the specified field changed.
* If it is not possible to set the value, because the field is not supported or for
* some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the adjustment is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEAR_OF_ERA} -
* Returns a {@code Year} with the specified year-of-era
* The era will be unchanged.
* <li>{@code YEAR} -
* Returns a {@code Year} with the specified year.
* This completely replaces the date and is equivalent to {@link #of(int)}.
* <li>{@code ERA} -
* Returns a {@code Year} with the specified era.
* The year-of-era will be unchanged.
* </ul>
* <p>
* In all cases, if the new value is outside the valid range of values for the field
* then a {@code DateTimeException} will be thrown.
* <p>
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
* passing {@code this} as the argument. In this case, the field determines
* whether and how to adjust the instant.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param field the field to set in the result, not null
* @param newValue the new value of the field in the result
* @return a {@code Year} based on {@code this} with the specified field set, not null
* @throws DateTimeException if the field cannot be set
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalField field, long newValue) {
if (field instanceof ChronoField) {
ChronoField f = (ChronoField) field;
f.checkValidValue(newValue);
switch (f) {
case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue));
case YEAR: return Year.of((int) newValue);
case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year));
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.adjustInto(this, newValue);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount added.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
* to implement the addition in any way it wishes, however it typically
* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount to add, not null
* @return a {@code Year} based on this year with the addition made, not null
* @throws DateTimeException if the addition cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(TemporalAmount amountToAdd) {
return (Year) amountToAdd.addTo(this);
}
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit added. If it is not possible to add the amount, because the
* unit is not supported or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoUnit} then the addition is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEARS} -
* Returns a {@code Year} with the specified number of years added.
* This is equivalent to {@link #plusYears(long)}.
* <li>{@code DECADES} -
* Returns a {@code Year} with the specified number of decades added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 10.
* <li>{@code CENTURIES} -
* Returns a {@code Year} with the specified number of centuries added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 100.
* <li>{@code MILLENNIA} -
* Returns a {@code Year} with the specified number of millennia added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 1,000.
* <li>{@code ERAS} -
* Returns a {@code Year} with the specified number of eras added.
* Only two eras are supported so the amount must be one, zero or minus one.
* If the amount is non-zero then the year is changed such that the year-of-era
* is unchanged.
* </ul>
* <p>
* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
* passing {@code this} as the argument. In this case, the unit determines
* whether and how to perform the addition.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount of the unit to add to the result, may be negative
* @param unit the unit of the amount to add, not null
* @return a {@code Year} based on this year with the specified amount added, not null
* @throws DateTimeException if the addition cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS: return plusYears(amountToAdd);
case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
/**
* Returns a copy of this year with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code Year} based on this year with the period added, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount subtracted.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
* to implement the subtraction in any way it wishes, however it typically
* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount to subtract, not null
* @return a {@code Year} based on this year with the subtraction made, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(TemporalAmount amountToSubtract) {
return (Year) amountToSubtract.subtractFrom(this);
}
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit subtracted. If it is not possible to subtract the amount,
* because the unit is not supported or for some other reason, an exception is thrown.
* <p>
* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
* See that method for a full description of how addition, and thus subtraction, works.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount of the unit to subtract from the result, may be negative
* @param unit the unit of the amount to subtract, not null
* @return a {@code Year} based on this year with the specified amount subtracted, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
/**
* Returns a copy of this year with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
* @return a {@code Year} based on this year with the period subtracted, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year minusYears(long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
}
//-----------------------------------------------------------------------
/**
* Queries this year using the specified query.
* <p>
* This queries this year using the specified query strategy object.
* The {@code TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
* @param query the query to invoke, not null
* @return the query result, null may be returned (defined by the query)
* @throws DateTimeException if unable to query (defined by the query)
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
*/
@SuppressWarnings("unchecked")
@Override
public <R> R query(TemporalQuery<R> query) {
if (query == TemporalQueries.chronology()) {
return (R) IsoChronology.INSTANCE;
} else if (query == TemporalQueries.precision()) {
return (R) YEARS;
}
return Temporal.super.query(query);
}
/**
* Adjusts the specified temporal object to have this year.
* <p>
* This returns a temporal object of the same observable type as the input
* with the year changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#YEAR} as the field.
* If the specified temporal object does not use the ISO calendar system then
* a {@code DateTimeException} is thrown.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisYear.adjustInto(temporal);
* temporal = temporal.with(thisYear);
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param temporal the target object to be adjusted, not null
* @return the adjusted object, not null
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Temporal adjustInto(Temporal temporal) {
if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
throw new DateTimeException("Adjustment only supported on ISO date-time");
}
return temporal.with(YEAR, year);
}
/**
* Calculates the amount of time until another year in terms of the specified unit.
* <p>
* This calculates the amount of time between two {@code Year}
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified year.
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code Year} using {@link #from(TemporalAccessor)}.
* For example, the period in decades between two year can be calculated
* using {@code startYear.until(endYear, DECADES)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two years.
* For example, the period in decades between 2012 and 2031
* will only be one decade as it is one year short of two decades.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method.
* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
* <pre>
* // these two lines are equivalent
* amount = start.until(end, YEARS);
* amount = YEARS.between(start, end);
* </pre>
* The choice should be made based on which makes the code more readable.
* <p>
* The calculation is implemented in this method for {@link ChronoUnit}.
* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
* {@code MILLENNIA} and {@code ERAS} are supported.
* Other {@code ChronoUnit} values will throw an exception.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
* passing {@code this} as the first argument and the converted input temporal
* as the second argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null
* @param unit the unit to measure the amount in, not null
* @return the amount of time between this year and the end year
* @throws DateTimeException if the amount cannot be calculated, or the end
* temporal cannot be converted to a {@code Year}
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
Year end = Year.from(endExclusive);
if (unit instanceof ChronoUnit) {
long yearsUntil = ((long) end.year) - year; // no overflow
switch ((ChronoUnit) unit) {
case YEARS: return yearsUntil;
case DECADES: return yearsUntil / 10;
case CENTURIES: return yearsUntil / 100;
case MILLENNIA: return yearsUntil / 1000;
case ERAS: return end.getLong(ERA) - getLong(ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
/**
* Formats this year using the specified formatter.
* <p>
* This year will be passed to the formatter to produce a string.
*
* @param formatter the formatter to use, not null
* @return the formatted year string, not null
* @throws DateTimeException if an error occurs during printing
*/
public String format(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.format(this);
}
//-----------------------------------------------------------------------
/**
* Combines this year with a day-of-year to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified day-of-year.
* <p>
* The day-of-year value 366 is only valid in a leap year.
*
* @param dayOfYear the day-of-year to use, not null
* @return the local date formed from this year and the specified date of year, not null
* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
* to 366 and this is not a leap year
*/
public LocalDate atDay(int dayOfYear) {
return LocalDate.ofYearDay(year, dayOfYear);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, not null
* @return the year-month formed from this year and the specified month, not null
*/
public YearMonth atMonth(Month month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, from 1 (January) to 12 (December)
* @return the year-month formed from this year and the specified month, not null
* @throws DateTimeException if the month is invalid
*/
public YearMonth atMonth(int month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month-day to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified month-day.
* <p>
* A month-day of February 29th will be adjusted to February 28th in the resulting
* date if the year is not a leap year.
*
* @param monthDay the month-day to use, not null
* @return the local date formed from this year and the specified month-day, not null
*/
public LocalDate atMonthDay(MonthDay monthDay) {
return monthDay.atYear(year);
}
//-----------------------------------------------------------------------
/**
* Compares this year to another year.
* <p>
* The comparison is based on the value of the year.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other year to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Year other) {
return year - other.year;
}
/**
* Is this year after the specified year.
*
* @param other the other year to compare to, not null
* @return true if this is after the specified year
*/
public boolean isAfter(Year other) {
return year > other.year;
}
/**
* Is this year before the specified year.
*
* @param other the other year to compare to, not null
* @return true if this point is before the specified year
*/
public boolean isBefore(Year other) {
return year < other.year;
}
//-----------------------------------------------------------------------
/**
* Checks if this year is equal to another year.
* <p>
* The comparison is based on the time-line position of the years.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other year
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Year) {
return year == ((Year) obj).year;
}
return false;
}
/**
* A hash code for this year.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return year;
}
//-----------------------------------------------------------------------
/**
* Outputs this year as a {@code String}.
*
* @return a string representation of this year, not null
*/
@Override
public String toString() {
return Integer.toString(year);
}
//-----------------------------------------------------------------------
/**
* Writes the object using a
* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
* @serialData
* <pre>
* out.writeByte(11); // identifies a Year
* out.writeInt(year);
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
private Object writeReplace() {
return new Ser(Ser.YEAR_TYPE, this);
}
/**
* Defend against malicious streams.
*
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
void writeExternal(DataOutput out) throws IOException {
out.writeInt(year);
}
static Year readExternal(DataInput in) throws IOException {
return Year.of(in.readInt());
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/java/time/Year.java | Java | mit | 47,803 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Process manager for *nix like system.
*
* @author andrew00x
*/
class UnixProcessManager extends ProcessManager {
/*
At the moment tested on linux only.
*/
private static final Logger LOG = LoggerFactory.getLogger(UnixProcessManager.class);
private static final CLibrary C_LIBRARY;
private static final Field PID_FIELD;
static {
CLibrary lib = null;
Field pidField = null;
if (SystemInfo.isUnix()) {
try {
lib = ((CLibrary)Native.loadLibrary("c", CLibrary.class));
} catch (Exception e) {
LOG.error("Cannot load native library", e);
}
try {
pidField = Thread.currentThread().getContextClassLoader().loadClass("java.lang.UNIXProcess").getDeclaredField("pid");
pidField.setAccessible(true);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
C_LIBRARY = lib;
PID_FIELD = pidField;
}
private static interface CLibrary extends Library {
// kill -l
int SIGKILL = 9;
int SIGTERM = 15;
int kill(int pid, int signal);
String strerror(int errno);
int system(String cmd);
}
private static final Pattern UNIX_PS_TABLE_PATTERN = Pattern.compile("\\s+");
@Override
public void kill(Process process) {
if (C_LIBRARY != null) {
killTree(getPid(process));
} else {
throw new IllegalStateException("Can't kill process. Not unix system?");
}
}
private void killTree(int pid) {
final int[] children = getChildProcesses(pid);
LOG.debug("PID: {}, child PIDs: {}", pid, children);
if (children.length > 0) {
for (int cpid : children) {
killTree(cpid); // kill process tree recursively
}
}
int r = C_LIBRARY.kill(pid, CLibrary.SIGKILL); // kill origin process
LOG.debug("kill {}", pid);
if (r != 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("kill for {} returns {}, strerror '{}'", pid, r, C_LIBRARY.strerror(r));
}
}
}
private int[] getChildProcesses(final int myPid) {
final String ps = "ps -e -o ppid,pid,comm"; /* PPID, PID, COMMAND */
final List<Integer> children = new ArrayList<>();
final StringBuilder error = new StringBuilder();
final LineConsumer stdout = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (line != null && !line.isEmpty()) {
final String[] tokens = UNIX_PS_TABLE_PATTERN.split(line.trim());
if (tokens.length == 3 /* PPID, PID, COMMAND */) {
int ppid;
try {
ppid = Integer.parseInt(tokens[0]);
} catch (NumberFormatException e) {
// May be first line from process table: 'PPID PID COMMAND'. Skip it.
return;
}
if (ppid == myPid) {
int pid = Integer.parseInt(tokens[1]);
children.add(pid);
}
}
}
}
@Override
public void close() throws IOException {
}
};
final LineConsumer stderr = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (error.length() > 0) {
error.append('\n');
}
error.append(line);
}
@Override
public void close() throws IOException {
}
};
try {
ProcessUtil.process(Runtime.getRuntime().exec(ps), stdout, stderr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (error.length() > 0) {
throw new IllegalStateException("can't get child processes: " + error.toString());
}
final int size = children.size();
final int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = children.get(i);
}
return result;
}
@Override
public boolean isAlive(Process process) {
return process.isAlive();
}
int getPid(Process process) {
if (PID_FIELD != null) {
try {
return ((Number)PID_FIELD.get(process)).intValue();
} catch (IllegalAccessException e) {
throw new IllegalStateException("Can't get process' pid. Not unix system?", e);
}
} else {
throw new IllegalStateException("Can't get process' pid. Not unix system?");
}
}
@Override
int system(String command) {
return C_LIBRARY.system(command);
}
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/UnixProcessManager.java | Java | epl-1.0 | 5,909 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ui.toolbar;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* This Lock Layer for Popup Menu uses as root for for Popup Menus and uses for closing all visible popups when user clicked outside one of
* them.
*
* @author Vitaliy Guliy
*/
public class MenuLockLayer extends AbsolutePanel {
/** Lock Layer uses for locking of screen. Uses for hiding popups. */
private class LockLayer extends AbsolutePanel {
public LockLayer() {
sinkEvents(Event.ONMOUSEDOWN);
}
@Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
close();
break;
}
}
}
/** Callback which is uses for closing Popup menu. */
private CloseMenuHandler closeMenuCallback;
private int topOffset = 20;
/** Create Menu Lock Layer. */
public MenuLockLayer() {
this(null, 0);
}
/**
* Create Menu Lock Layer.
*
* @param closeMenuCallback
* - callback which is uses for
*/
public MenuLockLayer(CloseMenuHandler closeMenuCallback) {
this(closeMenuCallback, 0);
}
public MenuLockLayer(CloseMenuHandler closeMenuCallback, int topOffset) {
this.closeMenuCallback = closeMenuCallback;
this.topOffset = topOffset;
getElement().setId("menu-lock-layer-id");
RootPanel.get().add(this, 0, topOffset);
getElement().getStyle().setProperty("right", "0px");
getElement().getStyle().setProperty("bottom", "0px");
getElement().getStyle().setProperty("zIndex", (Integer.MAX_VALUE - 5) + "");
AbsolutePanel blockMouseEventsPanel = new LockLayer();
blockMouseEventsPanel.setStyleName("exo-lockLayer");
blockMouseEventsPanel.getElement().getStyle().setProperty("position", "absolute");
blockMouseEventsPanel.getElement().getStyle().setProperty("left", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("top", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("right", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("bottom", "0px");
add(blockMouseEventsPanel);
}
public void close() {
removeFromParent();
if (closeMenuCallback != null) {
closeMenuCallback.onCloseMenu();
}
}
public int getTopOffset() {
return topOffset;
}
}
| gazarenkov/che-sketch | ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/toolbar/MenuLockLayer.java | Java | epl-1.0 | 3,234 |
package backtype.storm.state;
import java.util.List;
public interface ISynchronizeOutputCollector {
void add(int streamId, Object id, List<Object> tuple);
}
| revans2/storm | storm-core/src/jvm/backtype/storm/state/ISynchronizeOutputCollector.java | Java | epl-1.0 | 167 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.rest;
import javax.ws.rs.core.UriBuilder;
/**
* Helps to deliver context of RESTful request to components.
*
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
*/
public interface ServiceContext {
/**
* Get UriBuilder which already contains base URI of RESTful application and URL pattern of RESTful service that produces this
* instance.
*/
UriBuilder getServiceUriBuilder();
/** Get UriBuilder which already contains base URI of RESTful application. */
UriBuilder getBaseUriBuilder();
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ServiceContext.java | Java | epl-1.0 | 1,098 |
/*
* Copyright (C) 2011,2012,2013,2014 Samuel Audet
*
* This file is part of JavaCPP.
*
* JavaCPP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCPP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JavaCPP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacpp;
import com.googlecode.javacpp.annotation.Adapter;
import com.googlecode.javacpp.annotation.Allocator;
import com.googlecode.javacpp.annotation.ArrayAllocator;
import com.googlecode.javacpp.annotation.ByPtr;
import com.googlecode.javacpp.annotation.ByPtrPtr;
import com.googlecode.javacpp.annotation.ByPtrRef;
import com.googlecode.javacpp.annotation.ByRef;
import com.googlecode.javacpp.annotation.ByVal;
import com.googlecode.javacpp.annotation.Cast;
import com.googlecode.javacpp.annotation.Const;
import com.googlecode.javacpp.annotation.Convention;
import com.googlecode.javacpp.annotation.Function;
import com.googlecode.javacpp.annotation.Index;
import com.googlecode.javacpp.annotation.MemberGetter;
import com.googlecode.javacpp.annotation.MemberSetter;
import com.googlecode.javacpp.annotation.Name;
import com.googlecode.javacpp.annotation.Namespace;
import com.googlecode.javacpp.annotation.NoDeallocator;
import com.googlecode.javacpp.annotation.NoException;
import com.googlecode.javacpp.annotation.NoOffset;
import com.googlecode.javacpp.annotation.Opaque;
import com.googlecode.javacpp.annotation.Platform;
import com.googlecode.javacpp.annotation.Raw;
import com.googlecode.javacpp.annotation.ValueGetter;
import com.googlecode.javacpp.annotation.ValueSetter;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
/**
* The Generator is where all the C++ source code that we need gets generated.
* It has not been designed in any meaningful way since the requirements were
* not well understood. It is basically a prototype and is really quite a mess.
* Now that we understand better what we need, it could use some refactoring.
* <p>
* When attempting to understand what the Generator does, try to run experiments
* and inspect the generated code: It is quite readable.
* <p>
* Moreover, although Generator is the one ultimately doing something with the
* various annotations it relies on, it was easier to describe the behavior its
* meant to have with them as part of the documentation of the annotations, so
* we can refer to them to understand more about how Generator should work:
*
* @see Adapter
* @see Allocator
* @see ArrayAllocator
* @see ByPtr
* @see ByPtrPtr
* @see ByPtrRef
* @see ByRef
* @see ByVal
* @see Cast
* @see Const
* @see Convention
* @see Function
* @see Index
* @see MemberGetter
* @see MemberSetter
* @see Name
* @see Namespace
* @see NoDeallocator
* @see NoException
* @see NoOffset
* @see Opaque
* @see Platform
* @see Raw
* @see ValueGetter
* @see ValueSetter
*
* @author Samuel Audet
*/
public class Generator implements Closeable {
public Generator(Logger logger, Loader.ClassProperties properties) {
this.logger = logger;
this.properties = properties;
}
static class IndexedSet<E> extends LinkedHashMap<E,Integer> implements Iterable<E> {
public int index(E e) {
Integer i = get(e);
if (i == null) {
put(e, i = size());
}
return i;
}
public Iterator<E> iterator() {
return keySet().iterator();
}
}
static final String JNI_VERSION = "JNI_VERSION_1_4";
static final List<Class> baseClasses = Arrays.asList(new Class[] {
Pointer.class,
//FunctionPointer.class,
BytePointer.class,
ShortPointer.class,
IntPointer.class,
LongPointer.class,
FloatPointer.class,
DoublePointer.class,
CharPointer.class,
PointerPointer.class,
BoolPointer.class,
CLongPointer.class,
SizeTPointer.class });
final Logger logger;
final Loader.ClassProperties properties;
PrintWriter out, out2;
IndexedSet<String> callbacks;
IndexedSet<Class> functions, deallocators, arrayDeallocators, jclasses, jclassesInit;
HashMap<Class,LinkedList<String>> members;
boolean mayThrowExceptions, usesAdapters;
public boolean generate(String sourceFilename, String headerFilename,
String classPath, Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
jclassesInit = new IndexedSet<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
usesAdapters = false;
if (classes(true, true, classPath, classes)) {
// second pass with a real writer
out = new PrintWriter(sourceFilename);
if (headerFilename != null) {
out2 = new PrintWriter(headerFilename);
}
return classes(mayThrowExceptions, usesAdapters, classPath, classes);
} else {
return false;
}
}
public void close() {
if (out != null) {
out.close();
}
if (out2 != null) {
out2.close();
}
}
boolean classes(boolean handleExceptions, boolean defineAdapters, String classPath, Class<?> ... classes) {
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String warning = "// Generated by JavaCPP version " + version;
out.println(warning);
out.println();
if (out2 != null) {
out2.println(warning);
out2.println();
}
for (String s : properties.get("platform.define")) {
out.println("#define " + s);
}
out.println();
out.println("#ifdef __APPLE__");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))");
out.println(" #define JNIIMPORT");
out.println(" #define JNICALL");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#ifdef _WIN32");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __declspec(dllexport)");
out.println(" #define JNIIMPORT __declspec(dllimport)");
out.println(" #define JNICALL __stdcall");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#include <jni.h>");
if (out2 != null) {
out2.println("#include <jni.h>");
}
out.println("#ifdef ANDROID");
out.println(" #include <android/log.h>");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" #include <TargetConditionals.h>");
out.println(" #include <Foundation/Foundation.h>");
out.println("#endif");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)");
out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)");
out.println("#endif");
out.println();
out.println("#include <stddef.h>");
out.println("#ifndef _WIN32");
out.println(" #include <stdint.h>");
out.println("#endif");
out.println("#include <stdio.h>");
out.println("#include <stdlib.h>");
out.println("#include <string.h>");
out.println("#include <exception>");
out.println("#include <new>");
out.println();
out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))");
out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))");
out.println();
out.println("#if defined(_MSC_VER)");
out.println(" #define JavaCPP_noinline __declspec(noinline)");
out.println(" #define JavaCPP_hidden /* hidden by default */");
out.println("#elif defined(__GNUC__)");
out.println(" #define JavaCPP_noinline __attribute__((noinline))");
out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\")))");
out.println("#else");
out.println(" #define JavaCPP_noinline");
out.println(" #define JavaCPP_hidden");
out.println("#endif");
out.println();
List[] include = { properties.get("platform.include"),
properties.get("platform.cinclude") };
for (int i = 0; i < include.length; i++) {
if (include[i] != null && include[i].size() > 0) {
if (i == 1) {
out.println("extern \"C\" {");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
}
}
for (String s : (List<String>)include[i]) {
String line = "#include ";
if (!s.startsWith("<") && !s.startsWith("\"")) {
line += '"';
}
line += s;
if (!s.endsWith(">") && !s.endsWith("\"")) {
line += '"';
}
out.println(line);
if (out2 != null) {
out2.println(line);
}
}
if (i == 1) {
out.println("}");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
}
out.println();
}
}
out.println("static JavaVM* JavaCPP_vm = NULL;");
out.println("static bool JavaCPP_haveAllocObject = false;");
out.println("static bool JavaCPP_haveNonvirtual = false;");
out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {");
Iterator<Class> classIterator = jclasses.iterator();
int maxMemberSize = 0;
while (classIterator.hasNext()) {
Class c = classIterator.next();
out.print(" \"" + c.getName().replace('.','/') + "\"");
if (classIterator.hasNext()) {
out.println(",");
}
LinkedList<String> m = members.get(c);
if (m != null && m.size() > maxMemberSize) {
maxMemberSize = m.size();
}
}
out.println(" };");
out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };");
out.println("static jfieldID JavaCPP_addressFID = NULL;");
out.println("static jfieldID JavaCPP_positionFID = NULL;");
out.println("static jfieldID JavaCPP_limitFID = NULL;");
out.println("static jfieldID JavaCPP_capacityFID = NULL;");
out.println("static jmethodID JavaCPP_initMID = NULL;");
out.println("static jmethodID JavaCPP_toStringMID = NULL;");
out.println();
out.println("static inline void JavaCPP_log(const char* fmt, ...) {");
out.println(" va_list ap;");
out.println(" va_start(ap, fmt);");
out.println("#ifdef ANDROID");
out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);");
out.println("#else");
out.println(" vfprintf(stderr, fmt, ap);");
out.println(" fprintf(stderr, \"\\n\");");
out.println("#endif");
out.println(" va_end(ap);");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {");
out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {");
out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);");
out.println(" if (cls == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);");
out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" return JavaCPP_classes[i];");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);");
out.println(" if (fid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return fid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {");
out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" if (JavaCPP_haveAllocObject) {");
out.println(" return env->AllocObject(cls);");
out.println(" } else {");
out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting default constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" return env->NewObject(cls, mid);");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, int size, void (*deallocator)(void*)) {");
out.println(" if (deallocator != NULL) {");
out.println(" jvalue args[3];");
out.println(" args[0].j = ptr_to_jlong(ptr);");
out.println(" args[1].i = size;");
out.println(" args[2].j = ptr_to_jlong(deallocator);");
out.println(" if (JavaCPP_haveNonvirtual) {");
out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, "
+ jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);");
out.println(" } else {");
out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);");
out.println(" }");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));");
out.println(" env->SetIntField(obj, JavaCPP_limitFID, size);");
out.println(" env->SetIntField(obj, JavaCPP_capacityFID, size);");
out.println(" }");
out.println("}");
out.println();
out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {");
out.println("public:");
out.println(" JavaCPP_exception(const char* str) throw() {");
out.println(" if (str == NULL) {");
out.println(" strcpy(msg, \"Unknown exception.\");");
out.println(" } else {");
out.println(" strncpy(msg, str, sizeof(msg));");
out.println(" msg[sizeof(msg) - 1] = 0;");
out.println(" }");
out.println(" }");
out.println(" virtual const char* what() const throw() { return msg; }");
out.println(" char msg[1024];");
out.println("};");
out.println();
if (handleExceptions) {
out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {");
out.println(" jstring str = NULL;");
out.println(" try {");
out.println(" throw;");
out.println(" } catch (std::exception& e) {");
out.println(" str = env->NewStringUTF(e.what());");
out.println(" } catch (...) {");
out.println(" str = env->NewStringUTF(\"Unknown exception.\");");
out.println(" }");
out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");");
out.println(" if (mid == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);");
out.println("}");
out.println();
}
if (defineAdapters) {
out.println("#include <vector>");
out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {");
out.println("public:");
out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size) : ptr((P*)ptr), size(size),");
out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }");
out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), vec2(vec), vec(vec2) { }");
out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), vec(vec) { }");
out.println(" void assign(P* ptr, typename std::vector<T>::size_type size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" vec.assign(ptr, ptr + size);");
out.println(" }");
out.println(" static void deallocate(void* ptr) { delete[] (P*)ptr; }");
out.println(" operator P*() {");
out.println(" if (vec.size() > size) {");
out.println(" ptr = new (std::nothrow) P[vec.size()];");
out.println(" }");
out.println(" if (ptr) {");
out.println(" std::copy(vec.begin(), vec.end(), ptr);");
out.println(" }");
out.println(" size = vec.size();");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const P*() { return &vec[0]; }");
out.println(" operator std::vector<T>&() { return vec; }");
out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }");
out.println(" P* ptr;");
out.println(" typename std::vector<T>::size_type size;");
out.println(" std::vector<T> vec2;");
out.println(" std::vector<T>& vec;");
out.println("};");
out.println();
out.println("#include <string>");
out.println("class JavaCPP_hidden StringAdapter {");
out.println("public:");
out.println(" StringAdapter(const char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const signed char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const unsigned char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), str2(str), str(str2) { }");
out.println(" StringAdapter( std::string& str) : ptr(0), size(0), str(str) { }");
out.println(" void assign(char* ptr, size_t size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" str.assign(ptr ? ptr : \"\");");
out.println(" }");
out.println(" static void deallocate(void* ptr) { free(ptr); }");
out.println(" operator char*() {");
out.println(" const char* c_str = str.c_str();");
out.println(" if (ptr == NULL || strcmp(c_str, ptr) != 0) {");
out.println(" ptr = strdup(c_str);");
out.println(" }");
out.println(" size = strlen(c_str) + 1;");
out.println(" return ptr;");
out.println(" }");
out.println(" operator signed char*() { return (signed char*)(operator char*)(); }");
out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }");
out.println(" operator const char*() { return str.c_str(); }");
out.println(" operator const signed char*() { return (signed char*)str.c_str(); }");
out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }");
out.println(" operator std::string&() { return str; }");
out.println(" operator std::string*() { return ptr ? &str : 0; }");
out.println(" char* ptr;");
out.println(" size_t size;");
out.println(" std::string str2;");
out.println(" std::string& str;");
out.println("};");
out.println();
}
if (!functions.isEmpty()) {
out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {");
out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {");
out.println(" bool attached = false;");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" if (vm == NULL) {");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" int size = 1;");
out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {");
out.println("#endif");
}
out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");");
out.println(" *env = NULL;");
out.println(" return false;");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" }");
out.println("#endif");
}
out.println(" }");
out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" struct {");
out.println(" JNIEnv **env;");
out.println(" operator JNIEnv**() { return env; } // Android JNI");
out.println(" operator void**() { return (void**)env; } // standard JNI");
out.println(" } env2 = { env };");
out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" attached = true;");
out.println(" }");
out.println(" if (JavaCPP_vm == NULL) {");
out.println(" if (JNI_OnLoad(vm, NULL) < 0) {");
out.println(" JavaCPP_detach(attached);");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" }");
out.println(" return attached;");
out.println("}");
out.println();
}
for (Class c : functions) {
String[] typeName = cppTypeName(c);
String[] returnConvention = typeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = typeName[1].substring(1);
String instanceTypeName = functionClassName(c);
out.println("struct JavaCPP_hidden " + instanceTypeName + " {");
out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }");
out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";");
out.println(" " + typeName[0] + "ptr" + typeName[1] + ";");
out.println(" jobject obj; static jmethodID mid;");
out.println("};");
out.println("jmethodID " + instanceTypeName + "::mid = NULL;");
}
out.println();
for (String s : callbacks) {
out.println(s);
}
out.println();
for (Class c : deallocators) {
String name = "JavaCPP_" + mangle(c.getName());
out.print("static void " + name + "_deallocate(void *p) { ");
if (FunctionPointer.class.isAssignableFrom(c)) {
String typeName = functionClassName(c) + "*";
out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((("
+ typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }");
} else {
String[] typeName = cppTypeName(c);
out.println("delete (" + typeName[0] + typeName[1] + ")p; }");
}
}
for (Class c : arrayDeallocators) {
String name = "JavaCPP_" + mangle(c.getName());
String[] typeName = cppTypeName(c);
out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }");
}
out.println();
out.println("extern \"C\" {");
if (out2 != null) {
out2.println();
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
out2.println("JNIIMPORT int JavaCPP_init(int argc, const char *argv[]);");
out.println();
out.println("JNIEXPORT int JavaCPP_init(int argc, const char *argv[]) {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" if (JavaCPP_vm != NULL) {");
out.println(" return JNI_OK;");
out.println(" }");
out.println(" int err;");
out.println(" JavaVM *vm;");
out.println(" JNIEnv *env;");
out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);");
out.println(" JavaVMOption options[256] = { { NULL } };");
out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";");
out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {");
out.println(" options[i].optionString = (char*)argv[i - 1];");
out.println(" }");
out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };");
out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad(vm, NULL)) >= 0 ? JNI_OK : err;");
out.println("#endif");
out.println("}");
}
out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex
out.println("JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad().\");");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" if (JavaCPP_vm == vm) {");
out.println(" return env->GetVersion();");
out.println(" }");
out.println(" JavaCPP_vm = vm;");
out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;");
out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;");
out.println(" const char* members[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
LinkedList<String> m = members.get(classIterator.next());
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
out.print("\"" + memberIterator.next() + "\"");
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.println(" int offsets[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
Class c = classIterator.next();
LinkedList<String> m = members.get(c);
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String memberName = memberIterator.next();
if ("sizeof".equals(memberName)) {
if ("void".equals(valueTypeName)) {
valueTypeName = "void*";
}
out.print("sizeof(" + valueTypeName + ")");
} else {
out.print("offsetof(" + valueTypeName + ", " + memberName + ")");
}
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.print(" int memberOffsetSizes[" + jclasses.size() + "] = { ");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
LinkedList<String> m = members.get(classIterator.next());
out.print(m == null ? 0 : m.size());
if (classIterator.hasNext()) {
out.print(", ");
}
}
out.println(" };");
out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " +
jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)V\");");
out.println(" if (putMemberOffsetMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {");
out.println(" for (int j = 0; j < memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {");
out.println(" if (env->PushLocalFrame(2) == 0) {");
out.println(" jvalue args[3];");
out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);");
out.println(" args[1].l = env->NewStringUTF(members[i][j]);");
out.println(" args[2].i = offsets[i][j];");
out.println(" env->CallStaticVoidMethodA(JavaCPP_getClass(env, " +
jclasses.index(Loader.class) + "), putMemberOffsetMID, args);");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"address\", \"J\");");
out.println(" if (JavaCPP_addressFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"position\", \"I\");");
out.println(" if (JavaCPP_positionFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"limit\", \"I\");");
out.println(" if (JavaCPP_limitFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"capacity\", \"I\");");
out.println(" if (JavaCPP_capacityFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " +
jclasses.index(Pointer.class) + ", \"init\", \"(JIJ)V\");");
out.println(" if (JavaCPP_initMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " +
jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");");
out.println(" if (JavaCPP_toStringMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
classIterator = jclassesInit.iterator();
while (classIterator.hasNext()) {
Class c = classIterator.next();
if (c == Pointer.class) {
continue;
}
out.println(" if (JavaCPP_getClass(env, " + jclasses.index(c) + ") == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
}
out.println(" return env->GetVersion();");
out.println("}");
out.println();
if (out2 != null) {
out2.println("JNIIMPORT int JavaCPP_uninit();");
out2.println();
out.println("JNIEXPORT int JavaCPP_uninit() {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" JNI_OnUnload(JavaCPP_vm, NULL);");
out.println(" return vm->DestroyJavaVM();");
out.println("#endif");
out.println("}");
}
out.println();
out.println("JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad().\");");
out.println(" return;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {");
out.println(" env->DeleteWeakGlobalRef(JavaCPP_classes[i]);");
out.println(" JavaCPP_classes[i] = NULL;");
out.println(" }");
out.println(" JavaCPP_vm = NULL;");
out.println("}");
out.println();
for (Class<?> cls : baseClasses) {
methods(cls);
}
boolean didSomethingUseful = false;
for (Class<?> cls : classes) {
try {
didSomethingUseful |= methods(cls);
} catch (NoClassDefFoundError e) {
logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e);
}
}
out.println("}");
out.println();
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
return didSomethingUseful;
}
boolean methods(Class<?> cls) {
if (!checkPlatform(cls)) {
return false;
}
LinkedList<String> memberList = members.get(cls);
if (!cls.isAnnotationPresent(Opaque.class) &&
!FunctionPointer.class.isAssignableFrom(cls)) {
if (memberList == null) {
members.put(cls, memberList = new LinkedList<String>());
}
if (!memberList.contains("sizeof")) {
memberList.add("sizeof");
}
}
boolean didSomething = false;
for (Class<?> c : cls.getDeclaredClasses()) {
if (Pointer.class.isAssignableFrom(c) ||
Pointer.Deallocator.class.isAssignableFrom(c)) {
didSomething |= methods(c);
}
}
Method[] methods = cls.getDeclaredMethods();
boolean[] callbackAllocators = new boolean[methods.length];
Method functionMethod = functionMethod(cls, callbackAllocators);
boolean firstCallback = true;
for (int i = 0; i < methods.length; i++) {
String nativeName = mangle(cls.getName()) + "_" + mangle(methods[i].getName());
if (!checkPlatform(methods[i].getAnnotation(Platform.class))) {
continue;
}
MethodInformation methodInfo = methodInformation(methods[i]);
String callbackName = "JavaCPP_" + nativeName + "_callback";
if (callbackAllocators[i] && functionMethod == null) {
logger.warn("No callback method call() or apply() has been not declared in \"" +
cls.getCanonicalName() + "\". No code will be generated for callback allocator.");
continue;
} else if (callbackAllocators[i] || (methods[i].equals(functionMethod) && methodInfo == null)) {
functions.index(cls);
Name name = methods[i].getAnnotation(Name.class);
if (name != null && name.value().length > 0 && name.value()[0].length() > 0) {
callbackName = name.value()[0];
}
callback(cls, functionMethod, callbackName, firstCallback);
firstCallback = false;
didSomething = true;
}
if (methodInfo == null) {
continue;
}
if ((methodInfo.memberGetter || methodInfo.memberSetter) && !methodInfo.noOffset &&
memberList != null && !Modifier.isStatic(methodInfo.modifiers)) {
if (!memberList.contains(methodInfo.memberName[0])) {
memberList.add(methodInfo.memberName[0]);
}
}
didSomething = true;
out.print("JNIEXPORT " + jniTypeName(methodInfo.returnType) + " JNICALL Java_" + nativeName);
if (methodInfo.overloaded) {
out.print("__" + mangle(signature(methodInfo.parameterTypes)));
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print("(JNIEnv* env, jclass cls");
} else {
out.print("(JNIEnv* env, jobject obj");
}
for (int j = 0; j < methodInfo.parameterTypes.length; j++) {
out.print(", " + jniTypeName(methodInfo.parameterTypes[j]) + " arg" + j);
}
out.println(") {");
if (callbackAllocators[i]) {
callbackAllocator(cls, callbackName);
continue;
} else if (!Modifier.isStatic(methodInfo.modifiers) && !methodInfo.allocator &&
!methodInfo.arrayAllocator && !methodInfo.deallocator) {
// get our "this" pointer
String[] typeName = cppTypeName(cls);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
} else if (FunctionPointer.class.isAssignableFrom(cls)) {
functions.index(cls);
typeName[0] = functionClassName(cls) + "*";
typeName[1] = "";
}
out.println(" " + typeName[0] + " ptr" + typeName[1] + " = (" + typeName[0] +
typeName[1] + ")jlong_to_ptr(env->GetLongField(obj, JavaCPP_addressFID));");
out.println(" if (ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
if (FunctionPointer.class.isAssignableFrom(cls)) {
out.println(" if (ptr->ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This function pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (!cls.isAnnotationPresent(Opaque.class)) {
out.println(" jint position = env->GetIntField(obj, JavaCPP_positionFID);");
out.println(" ptr += position;");
if (methodInfo.bufferGetter) {
out.println(" jint size = env->GetIntField(obj, JavaCPP_limitFID);");
out.println(" size -= position;");
}
}
}
parametersBefore(methodInfo);
String returnPrefix = returnBefore(methodInfo);
call(methodInfo, returnPrefix);
returnAfter(methodInfo);
parametersAfter(methodInfo);
if (methodInfo.throwsException != null) {
out.println(" if (exc != NULL) {");
out.println(" env->Throw(exc);");
out.println(" }");
}
if (methodInfo.returnType != void.class) {
out.println(" return rarg;");
}
out.println("}");
}
out.println();
return didSomething;
}
void parametersBefore(MethodInformation methodInfo) {
String adapterLine = "";
AdapterInformation prevAdapterInfo = null;
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (!methodInfo.parameterTypes[j].isPrimitive()) {
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppTypeName(methodInfo.parameterTypes[j]);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
functions.index(methodInfo.parameterTypes[j]);
if (methodInfo.parameterTypes[j] == FunctionPointer.class) {
logger.warn("Method \"" + methodInfo.method + "\" has an abstract FunctionPointer parameter, " +
"but a concrete subclass is required. Compilation will most likely fail.");
}
typeName[0] = functionClassName(methodInfo.parameterTypes[j]) + "*";
typeName[1] = "";
}
if (typeName[0].length() == 0 || methodInfo.parameterRaw[j]) {
methodInfo.parameterRaw[j] = true;
typeName[0] = jniTypeName(methodInfo.parameterTypes[j]);
out.println(" " + typeName[0] + " ptr" + j + " = arg" + j + ";");
continue;
}
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
out.print(" " + typeName[0] + " ptr" + j + typeName[1] + " = ");
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] +
")jlong_to_ptr(env->GetLongField(arg" + j + ", JavaCPP_addressFID));");
if ((j == 0 && FunctionPointer.class.isAssignableFrom(methodInfo.cls) &&
methodInfo.cls.isAnnotationPresent(Namespace.class)) ||
passBy instanceof ByVal || passBy instanceof ByRef) {
// in the case of member ptr, ptr0 is our object pointer, which cannot be NULL
out.println(" if (ptr" + j + " == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Pointer address of argument " + j + " is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_limitFID);");
}
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint position" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_positionFID);");
out.println(" ptr" + j + " += position" + j + ";");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" size" + j + " -= position" + j + ";");
}
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println("arg" + j + " == NULL ? NULL : env->GetStringUTFChars(arg" + j + ", NULL);");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = 0;");
}
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print("arg" + j + " == NULL ? NULL : ");
String s = methodInfo.parameterTypes[j].getComponentType().getName();
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("(j" + s + "*)env->GetPrimitiveArrayCritical(arg" + j + ", NULL);");
} else {
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Get" + s + "ArrayElements(arg" + j + ", NULL);");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetArrayLength(arg" + j + ");");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] + ")env->GetDirectBufferAddress(arg" + j + ");");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetDirectBufferCapacity(arg" + j + ");");
}
} else {
out.println("arg" + j + ";");
logger.warn("Method \"" + methodInfo.method + "\" has an unsupported parameter of type \"" +
methodInfo.parameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
if (adapterInfo != null) {
usesAdapters = true;
adapterLine = " " + adapterInfo.name + " adapter" + j + "(";
prevAdapterInfo = adapterInfo;
}
if (prevAdapterInfo != null) {
if (!FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
// sometimes we need to use the Cast annotation for declaring functions only
adapterLine += cast;
}
adapterLine += "ptr" + j + ", size" + j;
if (--prevAdapterInfo.argc > 0) {
adapterLine += ", ";
}
}
if (prevAdapterInfo != null && prevAdapterInfo.argc <= 0) {
out.println(adapterLine + ");");
prevAdapterInfo = null;
}
}
}
}
String returnBefore(MethodInformation methodInfo) {
String returnPrefix = "";
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
if (methodInfo.cls != Pointer.class) {
out.println(" if (!env->IsSameObject(env->GetObjectClass(obj), JavaCPP_getClass(env, " +
jclasses.index(methodInfo.cls) + "))) {");
out.println(" return;");
out.println(" }");
}
String[] typeName = cppTypeName(methodInfo.cls);
returnPrefix = typeName[0] + " rptr" + typeName[1] + " = ";
}
} else {
String cast = cast(methodInfo.returnType, methodInfo.annotations);
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
out.println(" jobject rarg = obj;");
} else if (methodInfo.returnType.isPrimitive()) {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = 0;");
returnPrefix = typeName[0] + " rvalue" + typeName[1] + " = " + cast;
} else {
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
returnPrefix = "rptr = " + cast;
if (typeName[0].length() == 0 || methodInfo.returnRaw) {
methodInfo.returnRaw = true;
typeName[0] = jniTypeName(methodInfo.returnType);
out.println(" " + typeName[0] + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr;");
} else if (Pointer.class.isAssignableFrom(methodInfo.returnType) ||
Buffer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
functions.index(methodInfo.returnType);
typeName[0] = functionClassName(methodInfo.returnType) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
returnPrefix = "if (rptr != NULL) rptr->ptr = ";
}
if (returnBy instanceof ByVal) {
returnPrefix += (noException(methodInfo.returnType, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1] + "(";
} else if (returnBy instanceof ByRef) {
returnPrefix += "&";
} else if (returnBy instanceof ByPtrPtr) {
if (cast.length() > 0) {
typeName[0] = typeName[0].substring(0, typeName[0].length()-1);
}
returnPrefix = "rptr = NULL; " + typeName[0] + "* rptrptr" + typeName[1] + " = " + cast;
} // else ByPtr || ByPtrRef
if (methodInfo.bufferGetter) {
out.println(" jobject rarg = NULL;");
out.println(" char* rptr;");
} else {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr" + typeName[1] + ";");
}
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(" rptr = new (std::nothrow) " + valueTypeName + ";");
}
} else if (methodInfo.returnType == String.class) {
out.println(" jstring rarg = NULL;");
out.println(" const char* rptr;");
if (returnBy instanceof ByRef) {
returnPrefix = "std::string rstr(";
} else {
returnPrefix += "(const char*)";
}
} else {
logger.warn("Method \"" + methodInfo.method + "\" has unsupported return type \"" +
methodInfo.returnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
if (adapterInfo != null) {
usesAdapters = true;
returnPrefix = adapterInfo.name + " radapter(";
}
}
}
if (methodInfo.throwsException != null) {
out.println(" jthrowable exc = NULL;");
out.println(" try {");
}
return returnPrefix;
}
void call(MethodInformation methodInfo, String returnPrefix) {
String indent = methodInfo.throwsException != null ? " " : " ";
String prefix = "(";
String suffix = ")";
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
boolean index = methodInfo.method.isAnnotationPresent(Index.class) ||
(methodInfo.pairedMethod != null &&
methodInfo.pairedMethod.isAnnotationPresent(Index.class));
if (methodInfo.deallocator) {
out.println(indent + "void* allocatedAddress = jlong_to_ptr(arg0);");
out.println(indent + "void (*deallocatorAddress)(void*) = (void(*)(void*))jlong_to_ptr(arg1);");
out.println(indent + "if (deallocatorAddress != NULL && allocatedAddress != NULL) {");
out.println(indent + " (*deallocatorAddress)(allocatedAddress);");
out.println(indent + "}");
return; // nothing else should be appended here for deallocator
} else if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
boolean wantsPointer = false;
int k = methodInfo.parameterTypes.length-1;
if ((methodInfo.valueSetter || methodInfo.memberSetter) &&
!(by(methodInfo, k) instanceof ByRef) &&
adapterInformation(false, methodInfo, k) == null &&
methodInfo.parameterTypes[k] == String.class) {
// special considerations for char arrays as strings
out.print(indent + "strcpy((char*)");
wantsPointer = true;
prefix = ", ";
} else if (k >= 1 && methodInfo.parameterTypes[0].isArray() &&
methodInfo.parameterTypes[0].getComponentType().isPrimitive() &&
(methodInfo.parameterTypes[1] == int.class ||
methodInfo.parameterTypes[1] == long.class)) {
// special considerations for primitive arrays
out.print(indent + "memcpy(");
wantsPointer = true;
prefix = ", ";
if (methodInfo.memberGetter || methodInfo.valueGetter) {
out.print("ptr0 + arg1, ");
} else { // methodInfo.memberSetter || methodInfo.valueSetter
prefix += "ptr0 + arg1, ";
}
skipParameters = 2;
suffix = " * sizeof(*ptr0)" + suffix;
} else {
out.print(indent + returnPrefix);
prefix = methodInfo.valueGetter || methodInfo.memberGetter ? "" : " = ";
suffix = "";
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else if (methodInfo.memberGetter || methodInfo.memberSetter) {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
} else { // methodInfo.valueGetter || methodInfo.valueSetter
out.print(index ? "(*ptr)" : methodInfo.dim > 0 || wantsPointer ? "ptr" : "*ptr");
}
} else if (methodInfo.bufferGetter) {
out.print(indent + returnPrefix + "ptr");
prefix = "";
suffix = "";
} else { // function call
out.print(indent + returnPrefix);
if (FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
if (methodInfo.cls.isAnnotationPresent(Namespace.class)) {
out.print("(ptr0->*(ptr->ptr))");
skipParameters = 1;
} else {
out.print("(*ptr->ptr)");
}
} else if (methodInfo.allocator) {
String[] typeName = cppTypeName(methodInfo.cls);
String valueTypeName = valueTypeName(typeName);
if (methodInfo.cls == Pointer.class) {
// can't allocate a "void", so simply assign the argument instead
prefix = "";
suffix = "";
} else {
out.print((noException(methodInfo.cls, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1]);
if (methodInfo.arrayAllocator) {
prefix = "[";
suffix = "]";
}
}
} else if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
}
}
for (int j = skipParameters; j <= methodInfo.parameterTypes.length; j++) {
if (j == skipParameters + methodInfo.dim) {
if (methodInfo.memberName.length > 1) {
out.print(methodInfo.memberName[1]);
}
out.print(prefix);
if (methodInfo.withEnv) {
out.print(Modifier.isStatic(methodInfo.modifiers) ? "env, cls" : "env, obj");
if (methodInfo.parameterTypes.length - skipParameters - methodInfo.dim > 0) {
out.print(", ");
}
}
}
if (j == methodInfo.parameterTypes.length) {
break;
}
if (j < skipParameters + methodInfo.dim) {
// print array indices to access array members, or whatever
// the C++ operator does with them when the Index annotation is present
out.print("[");
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (("(void*)".equals(cast) || "(void *)".equals(cast)) &&
methodInfo.parameterTypes[j] == long.class) {
out.print("jlong_to_ptr(arg" + j + ")");
} else if (methodInfo.parameterTypes[j].isPrimitive()) {
out.print(cast + "arg" + j);
} else if (adapterInfo != null) {
cast = adapterInfo.cast.trim();
if (cast.length() > 0 && !cast.startsWith("(") && !cast.endsWith(")")) {
cast = "(" + cast + ")";
}
out.print(cast + "adapter" + j);
j += adapterInfo.argc - 1;
} else if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j]) && passBy == null) {
out.print(cast + "(ptr" + j + " == NULL ? NULL : ptr" + j + "->ptr)");
} else if (passBy instanceof ByVal || (passBy instanceof ByRef &&
methodInfo.parameterTypes[j] != String.class)) {
out.print("*" + cast + "ptr" + j);
} else if (passBy instanceof ByPtrPtr) {
out.print(cast + "(arg" + j + " == NULL ? NULL : &ptr" + j + ")");
} else { // ByPtr || ByPtrRef || (ByRef && std::string)
out.print(cast + "ptr" + j);
}
if (j < skipParameters + methodInfo.dim) {
out.print("]");
} else if (j < methodInfo.parameterTypes.length - 1) {
out.print(", ");
}
}
out.print(suffix);
if (methodInfo.memberName.length > 2) {
out.print(methodInfo.memberName[2]);
}
if (by(methodInfo.annotations) instanceof ByRef &&
methodInfo.returnType == String.class) {
// special considerations for std::string
out.print(");\n" + indent + "rptr = rstr.c_str()");
}
}
void returnAfter(MethodInformation methodInfo) {
String indent = methodInfo.throwsException != null ? " " : " ";
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
String suffix = methodInfo.deallocator ? "" : ";";
if (!methodInfo.returnType.isPrimitive() && adapterInfo != null) {
suffix = ")" + suffix;
}
if ((Pointer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) ||
Buffer.class.isAssignableFrom(methodInfo.returnType))) {
if (returnBy instanceof ByVal) {
suffix = ")" + suffix;
} else if (returnBy instanceof ByPtrPtr) {
out.println(suffix);
suffix = "";
out.println(indent + "if (rptrptr == NULL) {");
out.println(indent + " env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Return pointer address is NULL.\");");
out.println(indent + "} else {");
out.println(indent + " rptr = *rptrptr;");
out.println(indent + "}");
}
}
out.println(suffix);
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
out.println(indent + "jint rcapacity = " + (methodInfo.arrayAllocator ? "arg0;" : "1;"));
boolean noDeallocator = methodInfo.cls == Pointer.class ||
methodInfo.cls.isAnnotationPresent(NoDeallocator.class);
for (Annotation a : methodInfo.annotations) {
if (a instanceof NoDeallocator) {
noDeallocator = true;
break;
}
}
out.print(indent + "JavaCPP_initPointer(env, obj, rptr, rcapacity, ");
if (noDeallocator) {
out.println("NULL);");
} else if (methodInfo.arrayAllocator) {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocateArray);");
arrayDeallocators.index(methodInfo.cls);
} else {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocate);");
deallocators.index(methodInfo.cls);
}
}
} else {
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
// nothing
} else if (methodInfo.returnType.isPrimitive()) {
out.println(indent + "rarg = (" + jniTypeName(methodInfo.returnType) + ")rvalue;");
} else if (methodInfo.returnRaw) {
out.println(indent + "rarg = rptr;");
} else {
boolean needInit = false;
if (adapterInfo != null) {
out.println(indent + "rptr = radapter;");
if (methodInfo.returnType != String.class) {
out.println(indent + "jint rcapacity = (jint)radapter.size;");
out.println(indent + "void (*deallocator)(void*) = " +
(adapterInfo.constant ? "NULL;" : "&" + adapterInfo.name + "::deallocate;"));
}
needInit = true;
} else if (returnBy instanceof ByVal ||
FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(indent + "jint rcapacity = 1;");
out.println(indent + "void (*deallocator)(void*) = &JavaCPP_" +
mangle(methodInfo.returnType.getName()) + "_deallocate;");
deallocators.index(methodInfo.returnType);
needInit = true;
}
if (Pointer.class.isAssignableFrom(methodInfo.returnType)) {
out.print(indent);
if (!(returnBy instanceof ByVal)) {
// check if we can reuse one of the Pointer objects from the arguments
if (Modifier.isStatic(methodInfo.modifiers) && methodInfo.parameterTypes.length > 0) {
for (int i = 0; i < methodInfo.parameterTypes.length; i++) {
String cast = cast(methodInfo, i);
if (Arrays.equals(methodInfo.parameterAnnotations[i], methodInfo.annotations)
&& methodInfo.parameterTypes[i] == methodInfo.returnType) {
out.println( "if (rptr == " + cast + "ptr" + i + ") {");
out.println(indent + " rarg = arg" + i + ";");
out.print(indent + "} else ");
}
}
} else if (!Modifier.isStatic(methodInfo.modifiers) && methodInfo.cls == methodInfo.returnType) {
out.println( "if (rptr == ptr) {");
out.println(indent + " rarg = obj;");
out.print(indent + "} else ");
}
}
out.println( "if (rptr != NULL) {");
out.println(indent + " rarg = JavaCPP_createPointer(env, " + jclasses.index(methodInfo.returnType) +
(methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? ", arg0);" : ");"));
if (needInit) {
out.println(indent + " JavaCPP_initPointer(env, rarg, rptr, rcapacity, deallocator);");
} else {
out.println(indent + " env->SetLongField(rarg, JavaCPP_addressFID, ptr_to_jlong(rptr));");
}
out.println(indent + "}");
} else if (methodInfo.returnType == String.class) {
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewStringUTF(rptr);");
out.println(indent + "}");
} else if (methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) {
if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
String s = methodInfo.returnType.getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->New" + S + "Array(rcapacity);");
out.println(indent + " env->Set" + S + "ArrayRegion(rarg, 0, rcapacity, (j" + s + "*)rptr);");
out.println(indent + "}");
if (adapterInfo != null) {
out.println(indent + "if (deallocator != 0 && rptr != NULL) {");
out.println(indent + " (*(void(*)(void*))jlong_to_ptr(deallocator))((void*)rptr);");
out.println(indent + "}");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.returnType)) {
if (methodInfo.bufferGetter) {
out.println(indent + "jint rcapacity = size;");
} else if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewDirectByteBuffer((void*)rptr, rcapacity);");
out.println(indent + "}");
}
}
}
}
void parametersAfter(MethodInformation methodInfo) {
if (methodInfo.throwsException != null) {
mayThrowExceptions = true;
out.println(" } catch (...) {");
out.println(" exc = JavaCPP_handleException(env, " + jclasses.index(methodInfo.throwsException) + ");");
out.println(" }");
out.println();
}
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (methodInfo.parameterRaw[j]) {
continue;
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
AdapterInformation adapterInfo = adapterInformation(true, methodInfo, j);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
if (adapterInfo != null) {
for (int k = 0; k < adapterInfo.argc; k++) {
out.println(" " + typeName[0] + " rptr" + (j+k) + typeName[1] + " = " + cast + "adapter" + j + ";");
out.println(" jint rsize" + (j+k) + " = (jint)adapter" + j + ".size" + (k > 0 ? (k+1) + ";" : ";"));
out.println(" if (rptr" + (j+k) + " != " + cast + "ptr" + (j+k) + ") {");
out.println(" JavaCPP_initPointer(env, arg" + j + ", rptr" + (j+k) + ", rsize" + (j+k) + ", &" + adapterInfo.name + "::deallocate);");
out.println(" } else {");
out.println(" env->SetIntField(arg" + j + ", JavaCPP_limitFID, rsize" + (j+k) + " + position" + (j+k) + ");");
out.println(" }");
}
} else if ((passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) &&
!methodInfo.valueSetter && !methodInfo.memberSetter) {
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" ptr" + j + " -= position" + j + ";");
}
out.println(" if (arg" + j + " != NULL) env->SetLongField(arg" + j +
", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println(" if (arg" + j + " != NULL) env->ReleaseStringUTFChars(arg" + j + ", ptr" + j + ");");
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print(" if (arg" + j + " != NULL) ");
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("env->ReleasePrimitiveArrayCritical(arg" + j + ", ptr" + j + ", 0);");
} else {
String s = methodInfo.parameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Release" + S + "ArrayElements(arg" + j + ", (j" + s + "*)ptr" + j + ", 0);");
}
}
}
}
void callback(Class<?> cls, Method callbackMethod, String callbackName, boolean needFunctor) {
Class<?> callbackReturnType = callbackMethod.getReturnType();
Class<?>[] callbackParameterTypes = callbackMethod.getParameterTypes();
Annotation[] callbackAnnotations = callbackMethod.getAnnotations();
Annotation[][] callbackParameterAnnotations = callbackMethod.getParameterAnnotations();
String instanceTypeName = functionClassName(cls);
String[] callbackTypeName = cppTypeName(cls);
String[] returnConvention = callbackTypeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = callbackTypeName[1].substring(1);
callbacks.index("static " + instanceTypeName + " " + callbackName + "_instance;");
jclassesInit.index(cls); // for custom class loaders
if (out2 != null) {
out2.println("JNIIMPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + ";");
}
out.println("JNIEXPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + " {");
out.print((callbackReturnType != void.class ? " return " : " ") + callbackName + "_instance(");
for (int j = 0; j < callbackParameterTypes.length; j++) {
out.print("arg" + j);
if (j < callbackParameterTypes.length - 1) {
out.print(", ");
}
}
out.println(");");
out.println("}");
if (!needFunctor) {
return;
}
out.println(returnConvention[0] + instanceTypeName + "::operator()" + parameterDeclaration + " {");
String returnPrefix = "";
if (callbackReturnType != void.class) {
out.println(" " + jniTypeName(callbackReturnType) + " rarg = 0;");
returnPrefix = "rarg = ";
if (callbackReturnType == String.class) {
returnPrefix += "(jstring)";
}
}
String callbackReturnCast = cast(callbackReturnType, callbackAnnotations);
Annotation returnBy = by(callbackAnnotations);
String[] returnTypeName = cppTypeName(callbackReturnType);
String returnValueTypeName = valueTypeName(returnTypeName);
AdapterInformation returnAdapterInfo = adapterInformation(false, returnValueTypeName, callbackAnnotations);
out.println(" jthrowable exc = NULL;");
out.println(" JNIEnv* env;");
out.println(" bool attached = JavaCPP_getEnv(&env);");
out.println(" if (env == NULL) {");
out.println(" goto end;");
out.println(" }");
out.println("{");
if (callbackParameterTypes.length > 0) {
out.println(" jvalue args[" + callbackParameterTypes.length + "];");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (callbackParameterTypes[j].isPrimitive()) {
out.println(" args[" + j + "]." +
signature(callbackParameterTypes[j]).toLowerCase() + " = (" +
jniTypeName(callbackParameterTypes[j]) + ")arg" + j + ";");
} else {
Annotation passBy = by(callbackParameterAnnotations[j]);
String[] typeName = cppTypeName(callbackParameterTypes[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, callbackParameterAnnotations[j]);
boolean needInit = false;
if (adapterInfo != null) {
usesAdapters = true;
out.println(" " + adapterInfo.name + " adapter" + j + "(arg" + j + ");");
if (callbackParameterTypes[j] != String.class) {
out.println(" jint size" + j + " = (jint)adapter" + j + ".size;");
out.println(" void (*deallocator" + j + ")(void*) = &" + adapterInfo.name + "::deallocate;");
}
needInit = true;
} else if ((passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) ||
FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" jint size" + j + " = 1;");
out.println(" void (*deallocator" + j + ")(void*) = &JavaCPP_" +
mangle(callbackParameterTypes[j].getName()) + "_deallocate;");
deallocators.index(callbackParameterTypes[j]);
needInit = true;
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j]) ||
Buffer.class.isAssignableFrom(callbackParameterTypes[j]) ||
(callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
functions.index(callbackParameterTypes[j]);
typeName[0] = functionClassName(callbackParameterTypes[j]) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
}
out.println(" " + jniTypeName(callbackParameterTypes[j]) + " obj" + j + " = NULL;");
out.println(" " + typeName[0] + " ptr" + j + typeName[1] + " = NULL;");
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" ptr" + j + " = new (std::nothrow) " + valueTypeName + ";");
out.println(" if (ptr" + j + " != NULL) {");
out.println(" ptr" + j + "->ptr = arg" + j + ";");
out.println(" }");
} else if (adapterInfo != null) {
out.println(" ptr" + j + " = adapter" + j + ";");
} else if (passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) {
out.println(" ptr" + j + (noException(callbackParameterTypes[j], callbackMethod) ?
" = new (std::nothrow) " : " = new ") + valueTypeName + typeName[1] +
"(*(" + typeName[0] + typeName[1] + ")&arg" + j + ");");
} else if (passBy instanceof ByVal || passBy instanceof ByRef) {
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")&arg" + j + ";");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " == NULL) {");
out.println(" JavaCPP_log(\"Pointer address of argument " + j + " is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else {");
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")*arg" + j + ";");
out.println(" }");
} else { // ByPtr || ByPtrRef
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")arg" + j + ";");
}
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String s = " obj" + j + " = JavaCPP_createPointer(env, " + jclasses.index(callbackParameterTypes[j]) + ");";
jclassesInit.index(callbackParameterTypes[j]); // for custom class loaders
adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(s);
} else {
out.println(" if (ptr" + j + " != NULL) { ");
out.println(" " + s);
out.println(" }");
}
out.println(" if (obj" + j + " != NULL) { ");
if (needInit) {
out.println(" JavaCPP_initPointer(env, obj" + j + ", ptr" + j + ", size" + j + ", deallocator" + j + ");");
} else {
out.println(" env->SetLongField(obj" + j + ", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
out.println(" }");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j] == String.class) {
out.println(" jstring obj" + j + " = (const char*)" + (adapterInfo != null ? "adapter" : "arg") + j +
" == NULL ? NULL : env->NewStringUTF((const char*)" + (adapterInfo != null ? "adapter" : "arg") + j + ");");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive()) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
String s = callbackParameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->New" + S + "Array(size"+ j + ");");
out.println(" env->Set" + S + "ArrayRegion(obj" + j + ", 0, size" + j + ", (j" + s + "*)ptr" + j + ");");
out.println(" }");
if (adapterInfo != null) {
out.println(" if (deallocator" + j + " != 0 && ptr" + j + " != NULL) {");
out.println(" (*(void(*)(void*))jlong_to_ptr(deallocator" + j + "))((void*)ptr" + j + ");");
out.println(" }");
}
} else if (Buffer.class.isAssignableFrom(callbackParameterTypes[j])) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->NewDirectByteBuffer((void*)ptr" + j + ", size" + j + ");");
out.println(" }");
} else {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported parameter type \"" +
callbackParameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
}
}
}
out.println(" if (obj == NULL) {");
out.println(" obj = env->NewGlobalRef(JavaCPP_createPointer(env, " + jclasses.index(cls) + "));");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(this));");
out.println(" }");
out.println(" ptr = &" + callbackName + ";");
out.println(" }");
out.println(" if (mid == NULL) {");
out.println(" mid = JavaCPP_getMethodID(env, " + jclasses.index(cls) + ", \"" + callbackMethod.getName() + "\", \"(" +
signature(callbackMethod.getParameterTypes()) + ")" + signature(callbackMethod.getReturnType()) + "\");");
out.println(" }");
out.println(" if (env->IsSameObject(obj, NULL)) {");
out.println(" JavaCPP_log(\"Function pointer object is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else if (mid == NULL) {");
out.println(" JavaCPP_log(\"Error getting method ID of function caller \\\"" + callbackMethod + "\\\" for callback.\");");
out.println(" } else {");
String s = "Object";
if (callbackReturnType.isPrimitive()) {
s = callbackReturnType.getName();
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
out.println(" " + returnPrefix + "env->Call" + s + "MethodA(obj, mid, " + (callbackParameterTypes.length == 0 ? "NULL);" : "args);"));
out.println(" if ((exc = env->ExceptionOccurred()) != NULL) {");
out.println(" env->ExceptionClear();");
out.println(" }");
out.println(" }");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String[] typeName = cppTypeName(callbackParameterTypes[j]);
Annotation passBy = by(callbackParameterAnnotations[j]);
String cast = cast(callbackParameterTypes[j], callbackParameterAnnotations[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(" " + typeName[0] + " rptr" + j + typeName[1] + " = (" +
typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(obj" + j + ", JavaCPP_addressFID));");
if (adapterInfo != null) {
out.println(" jint rsize" + j + " = env->GetIntField(obj" + j + ", JavaCPP_limitFID);");
}
if (!callbackParameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition" + j + " = env->GetIntField(obj" + j + ", JavaCPP_positionFID);");
out.println(" rptr" + j + " += rposition" + j + ";");
if (adapterInfo != null) {
out.println(" rsize" + j + " -= rposition" + j + ";");
}
}
if (adapterInfo != null) {
out.println(" adapter" + j + ".assign(rptr" + j + ", rsize" + j + ");");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " != NULL) {");
out.println(" *arg" + j + " = *" + cast + "&rptr" + j + ";");
out.println(" }");
} else if (passBy instanceof ByPtrRef) {
out.println(" arg" + j + " = " + cast + "rptr" + j + ";");
}
}
}
if (!callbackParameterTypes[j].isPrimitive()) {
out.println(" env->DeleteLocalRef(obj" + j + ");");
}
}
out.println("}");
out.println("end:");
if (callbackReturnType != void.class) {
if ("void*".equals(returnTypeName[0])) {
returnTypeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : (" +
returnTypeName[0] + returnTypeName[1] + ")jlong_to_ptr(env->GetLongField(rarg, JavaCPP_addressFID));");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_limitFID);");
}
if (!callbackReturnType.isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_positionFID);");
out.println(" rptr += rposition;");
if (returnAdapterInfo != null) {
out.println(" rsize -= rposition;");
}
}
} else if (callbackReturnType == String.class) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetStringUTFChars(rarg, NULL);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = 0;");
}
} else if (Buffer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetDirectBufferAddress(rarg);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetDirectBufferCapacity(rarg);");
}
} else if (!callbackReturnType.isPrimitive()) {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported return type \"" +
callbackReturnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
}
out.println(" if (exc != NULL) {");
out.println(" jstring str = (jstring)env->CallObjectMethod(exc, JavaCPP_toStringMID);");
out.println(" env->DeleteLocalRef(exc);");
out.println(" const char *msg = env->GetStringUTFChars(str, NULL);");
out.println(" JavaCPP_exception e(msg);");
out.println(" env->ReleaseStringUTFChars(str, msg);");
out.println(" env->DeleteLocalRef(str);");
out.println(" JavaCPP_detach(attached);");
out.println(" throw e;");
out.println(" } else {");
out.println(" JavaCPP_detach(attached);");
out.println(" }");
if (callbackReturnType != void.class) {
if (callbackReturnType.isPrimitive()) {
out.println(" return " + callbackReturnCast + "rarg;");
} else if (returnAdapterInfo != null) {
usesAdapters = true;
out.println(" return " + returnAdapterInfo.name + "(" + callbackReturnCast + "rptr, rsize);");
} else if (FunctionPointer.class.isAssignableFrom(callbackReturnType)) {
functions.index(callbackReturnType);
out.println(" return " + callbackReturnCast + "(rptr == NULL ? NULL : rptr->ptr);");
} else if (returnBy instanceof ByVal || returnBy instanceof ByRef) {
out.println(" if (rptr == NULL) {");
out.println(" JavaCPP_log(\"Return pointer address is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" static " + returnValueTypeName + " empty" + returnTypeName[1] + ";");
out.println(" return empty;");
out.println(" } else {");
out.println(" return *" + callbackReturnCast + "rptr;");
out.println(" }");
} else if (returnBy instanceof ByPtrPtr) {
out.println(" return " + callbackReturnCast + "&rptr;");
} else { // ByPtr || ByPtrRef
out.println(" return " + callbackReturnCast + "rptr;");
}
}
out.println("}");
}
void callbackAllocator(Class cls, String callbackName) {
// XXX: Here, we should actually allocate new trampolines on the heap somehow...
// For now it just bumps out from the global variable the last object that called this method
String instanceTypeName = functionClassName(cls);
out.println(" obj = env->NewWeakGlobalRef(obj);");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" return;");
out.println(" }");
out.println(" " + instanceTypeName + "* rptr = new (std::nothrow) " + instanceTypeName + ";");
out.println(" if (rptr != NULL) {");
out.println(" rptr->ptr = &" + callbackName + ";");
out.println(" rptr->obj = obj;");
out.println(" JavaCPP_initPointer(env, obj, rptr, 1, &JavaCPP_" + mangle(cls.getName()) + "_deallocate);");
deallocators.index(cls);
out.println(" " + callbackName + "_instance = *rptr;");
out.println(" }");
out.println("}");
}
boolean checkPlatform(Class<?> cls) {
com.googlecode.javacpp.annotation.Properties classProperties =
cls.getAnnotation(com.googlecode.javacpp.annotation.Properties.class);
if (classProperties != null) {
Class[] classes = classProperties.inherit();
if (classes != null) {
for (Class c : classes) {
if (checkPlatform(c)) {
return true;
}
}
}
Platform[] platforms = classProperties.value();
if (platforms != null) {
for (Platform p : platforms) {
if (checkPlatform(p)) {
return true;
}
}
}
} else if (checkPlatform(cls.getAnnotation(Platform.class))) {
return true;
}
return false;
}
boolean checkPlatform(Platform platform) {
if (platform == null) {
return true;
}
String platform2 = properties.getProperty("platform");
String[][] names = { platform.value(), platform.not() };
boolean[] matches = { false, false };
for (int i = 0; i < names.length; i++) {
for (String s : names[i]) {
if (platform2.startsWith(s)) {
matches[i] = true;
break;
}
}
}
if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) {
return true;
}
return false;
}
static String functionClassName(Class<?> cls) {
Name name = cls.getAnnotation(Name.class);
return name != null ? name.value()[0] : "JavaCPP_" + mangle(cls.getName());
}
static Method functionMethod(Class<?> cls, boolean[] callbackAllocators) {
if (!FunctionPointer.class.isAssignableFrom(cls)) {
return null;
}
Method[] methods = cls.getDeclaredMethods();
Method functionMethod = null;
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
int modifiers = methods[i].getModifiers();
Class[] parameterTypes = methods[i].getParameterTypes();
Class returnType = methods[i].getReturnType();
if (Modifier.isStatic(modifiers)) {
continue;
}
if (callbackAllocators != null && methodName.startsWith("allocate") &&
Modifier.isNative(modifiers) && returnType == void.class &&
parameterTypes.length == 0) {
// found a callback allocator method
callbackAllocators[i] = true;
} else if (methodName.startsWith("call") || methodName.startsWith("apply")) {
// found a function caller method and/or callback method
functionMethod = methods[i];
}
}
return functionMethod;
}
static class MethodInformation {
Class<?> cls;
Method method;
Annotation[] annotations;
int modifiers;
Class<?> returnType;
String name, memberName[];
int dim;
boolean[] parameterRaw;
Class<?>[] parameterTypes;
Annotation[][] parameterAnnotations;
boolean returnRaw, withEnv, overloaded, noOffset, deallocator, allocator, arrayAllocator,
bufferGetter, valueGetter, valueSetter, memberGetter, memberSetter, noReturnGetter;
Method pairedMethod;
Class<?> throwsException;
}
MethodInformation methodInformation(Method method) {
if (!Modifier.isNative(method.getModifiers())) {
return null;
}
MethodInformation info = new MethodInformation();
info.cls = method.getDeclaringClass();
info.method = method;
info.annotations = method.getAnnotations();
info.modifiers = method.getModifiers();
info.returnType = method.getReturnType();
info.name = method.getName();
Name name = method.getAnnotation(Name.class);
info.memberName = name != null ? name.value() : new String[] { info.name };
Index index = method.getAnnotation(Index.class);
info.dim = index != null ? index.value() : 0;
info.parameterTypes = method.getParameterTypes();
info.parameterAnnotations = method.getParameterAnnotations();
info.returnRaw = method.isAnnotationPresent(Raw.class);
info.withEnv = info.returnRaw ? method.getAnnotation(Raw.class).withEnv() : false;
info.parameterRaw = new boolean[info.parameterAnnotations.length];
for (int i = 0; i < info.parameterAnnotations.length; i++) {
for (int j = 0; j < info.parameterAnnotations[i].length; j++) {
if (info.parameterAnnotations[i][j] instanceof Raw) {
info.parameterRaw[i] = true;
info.withEnv |= ((Raw)info.parameterAnnotations[i][j]).withEnv();
}
}
}
boolean canBeGetter = info.returnType != void.class || (info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive());
boolean canBeSetter = (info.returnType == void.class ||
info.returnType == info.cls) && info.parameterTypes.length > 0;
boolean canBeAllocator = !Modifier.isStatic(info.modifiers) && info.returnType == void.class;
boolean canBeArrayAllocator = canBeAllocator && info.parameterTypes.length == 1 &&
(info.parameterTypes[0] == int.class || info.parameterTypes[0] == long.class);
boolean valueGetter = false;
boolean valueSetter = false;
boolean memberGetter = false;
boolean memberSetter = false;
boolean noReturnGetter = false;
Method pairedMethod = null;
for (Method method2 : info.cls.getDeclaredMethods()) {
int modifiers2 = method2.getModifiers();
Class returnType2 = method2.getReturnType();
String methodName2 = method2.getName();
Class[] parameterTypes2 = method2.getParameterTypes();
Annotation[] annotations2 = method2.getAnnotations();
Annotation[][] parameterAnnotations2 = method2.getParameterAnnotations();
int skipParameters = info.parameterTypes.length > 0 && info.parameterTypes[0] == Class.class ? 1 : 0;
int skipParameters2 = parameterTypes2.length > 0 && parameterTypes2[0] == Class.class ? 1 : 0;
if (method.equals(method2) || !Modifier.isNative(modifiers2)) {
continue;
}
boolean canBeValueGetter = false;
boolean canBeValueSetter = false;
boolean canBeMemberGetter = false;
boolean canBeMemberSetter = false;
if (canBeGetter && "get".equals(info.name) && "put".equals(methodName2)) {
canBeValueGetter = true;
} else if (canBeSetter && "put".equals(info.name) && "get".equals(methodName2)) {
canBeValueSetter = true;
} else if (methodName2.equals(info.name)) {
info.overloaded = true;
canBeMemberGetter = canBeGetter;
canBeMemberSetter = canBeSetter;
for (int j = skipParameters; j < info.parameterTypes.length; j++) {
if (info.parameterTypes[j] != int.class && info.parameterTypes[j] != long.class) {
canBeMemberGetter = false;
if (j < info.parameterTypes.length - 1) {
canBeMemberSetter = false;
}
}
}
} else {
continue;
}
boolean sameIndexParameters = true;
for (int j = 0; j < info.parameterTypes.length - skipParameters && j < parameterTypes2.length - skipParameters2; j++) {
if (info.parameterTypes[j + skipParameters] != parameterTypes2[j + skipParameters2]) {
sameIndexParameters = false;
}
}
if (!sameIndexParameters) {
continue;
}
boolean parameterAsReturn = canBeValueGetter && info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive();
boolean parameterAsReturn2 = canBeValueSetter && parameterTypes2.length > 0 &&
parameterTypes2[0].isArray() && parameterTypes2[0].getComponentType().isPrimitive();
if (canBeGetter && parameterTypes2.length - (parameterAsReturn ? 0 : 1) == info.parameterTypes.length - skipParameters
&& (parameterAsReturn ? info.parameterTypes[info.parameterTypes.length - 1] : info.returnType) ==
parameterTypes2[parameterTypes2.length - 1] && (returnType2 == void.class || returnType2 == info.cls)
&& (parameterAnnotations2[parameterAnnotations2.length - 1].length == 0
|| (Arrays.equals(parameterAnnotations2[parameterAnnotations2.length - 1], info.annotations)))) {
pairedMethod = method2;
valueGetter = canBeValueGetter;
memberGetter = canBeMemberGetter;
noReturnGetter = parameterAsReturn;
} else if (canBeSetter && info.parameterTypes.length - (parameterAsReturn2 ? 0 : 1) == parameterTypes2.length - skipParameters2
&& (parameterAsReturn2 ? parameterTypes2[parameterTypes2.length - 1] : returnType2) ==
info.parameterTypes[info.parameterTypes.length - 1] && (info.returnType == void.class || info.returnType == info.cls)
&& (info.parameterAnnotations[info.parameterAnnotations.length - 1].length == 0
|| (Arrays.equals(info.parameterAnnotations[info.parameterAnnotations.length - 1], annotations2)))) {
pairedMethod = method2;
valueSetter = canBeValueSetter;
memberSetter = canBeMemberSetter;
}
}
Annotation behavior = behavior(info.annotations);
if (canBeGetter && behavior instanceof ValueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof ValueSetter) {
info.valueSetter = true;
} else if (canBeGetter && behavior instanceof MemberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof MemberSetter) {
info.memberSetter = true;
} else if (canBeAllocator && behavior instanceof Allocator) {
info.allocator = true;
} else if (canBeArrayAllocator && behavior instanceof ArrayAllocator) {
info.allocator = info.arrayAllocator = true;
} else if (behavior == null) {
// try to guess the behavior of the method
if (info.returnType == void.class && "deallocate".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 2 &&
info.parameterTypes[0] == long.class && info.parameterTypes[1] == long.class) {
info.deallocator = true;
} else if (canBeAllocator && "allocate".equals(info.name)) {
info.allocator = true;
} else if (canBeArrayAllocator && "allocateArray".equals(info.name)) {
info.allocator = info.arrayAllocator = true;
} else if (info.returnType.isAssignableFrom(ByteBuffer.class) && "asDirectBuffer".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 0) {
info.bufferGetter = true;
} else if (valueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (valueSetter) {
info.valueSetter = true;
info.pairedMethod = pairedMethod;
} else if (memberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (memberSetter) {
info.memberSetter = true;
info.pairedMethod = pairedMethod;
}
} else if (!(behavior instanceof Function)) {
logger.warn("Method \"" + method + "\" cannot behave like a \"" +
behavior.annotationType().getSimpleName() + "\". No code will be generated.");
return null;
}
if (name == null && info.pairedMethod != null) {
name = info.pairedMethod.getAnnotation(Name.class);
if (name != null) {
info.memberName = name.value();
}
}
info.noOffset = info.cls.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(Index.class);
if (!info.noOffset && info.pairedMethod != null) {
info.noOffset = info.pairedMethod.isAnnotationPresent(NoOffset.class) ||
info.pairedMethod.isAnnotationPresent(Index.class);
}
if (info.parameterTypes.length == 0 || !info.parameterTypes[0].isArray()) {
if (info.valueGetter || info.memberGetter) {
info.dim = info.parameterTypes.length;
} else if (info.memberSetter || info.valueSetter) {
info.dim = info.parameterTypes.length-1;
}
}
info.throwsException = null;
if (!noException(info.cls, method)) {
if ((by(info.annotations) instanceof ByVal && !noException(info.returnType, method)) ||
!info.deallocator && !info.valueGetter && !info.valueSetter &&
!info.memberGetter && !info.memberSetter && !info.bufferGetter) {
Class<?>[] exceptions = method.getExceptionTypes();
info.throwsException = exceptions.length > 0 ? exceptions[0] : RuntimeException.class;
}
}
return info;
}
static boolean noException(Class<?> cls, Method method) {
boolean noException = baseClasses.contains(cls) ||
method.isAnnotationPresent(NoException.class);
while (!noException && cls != null) {
if (noException = cls.isAnnotationPresent(NoException.class)) {
break;
}
cls = cls.getDeclaringClass();
}
return noException;
}
static class AdapterInformation {
String name;
int argc;
String cast;
boolean constant;
}
AdapterInformation adapterInformation(boolean out, MethodInformation methodInfo, int j) {
if (out && (methodInfo.parameterTypes[j] == String.class || methodInfo.valueSetter || methodInfo.memberSetter)) {
return null;
}
String typeName = cast(methodInfo, j);
if (typeName != null && typeName.startsWith("(") && typeName.endsWith(")")) {
typeName = typeName.substring(1, typeName.length()-1);
}
if (typeName == null || typeName.length() == 0) {
typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j])[0];
}
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapter = adapterInformation(out, valueTypeName, methodInfo.parameterAnnotations[j]);
if (adapter == null && methodInfo.pairedMethod != null && j == methodInfo.parameterTypes.length - 1 &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
adapter = adapterInformation(out, valueTypeName, methodInfo.pairedMethod.getAnnotations());
}
return adapter;
}
AdapterInformation adapterInformation(boolean out, String valueTypeName, Annotation ... annotations) {
AdapterInformation adapterInfo = null;
boolean constant = false;
String cast = "";
for (Annotation a : annotations) {
Adapter adapter = a instanceof Adapter ? (Adapter)a : a.annotationType().getAnnotation(Adapter.class);
if (adapter != null) {
adapterInfo = new AdapterInformation();
adapterInfo.name = adapter.value();
adapterInfo.argc = adapter.argc();
if (a != adapter) {
try {
Class cls = a.annotationType();
if (cls.isAnnotationPresent(Const.class)) {
constant = true;
}
try {
String value = cls.getDeclaredMethod("value").invoke(a).toString();
if (value != null && value.length() > 0) {
valueTypeName = value;
}
// else use inferred type
} catch (NoSuchMethodException e) {
// this adapter does not support a template type
valueTypeName = null;
}
Cast c = (Cast)cls.getAnnotation(Cast.class);
if (c != null && cast.length() == 0) {
cast = c.value()[0];
if (valueTypeName != null) {
cast += "< " + valueTypeName + " >";
}
if (c.value().length > 1) {
cast += c.value()[1];
}
}
} catch (Exception ex) {
logger.warn("Could not invoke the value() method on annotation \"" + a + "\": " + ex);
}
if (valueTypeName != null && valueTypeName.length() > 0) {
adapterInfo.name += "< " + valueTypeName + " >";
}
}
} else if (a instanceof Const) {
constant = true;
} else if (a instanceof Cast) {
Cast c = ((Cast)a);
if (c.value().length > 1) {
cast = c.value()[1];
}
}
}
if (adapterInfo != null) {
adapterInfo.cast = cast;
adapterInfo.constant = constant;
}
return out && constant ? null : adapterInfo;
}
String cast(MethodInformation methodInfo, int j) {
String cast = cast(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
if ((cast == null || cast.length() == 0) && j == methodInfo.parameterTypes.length-1 &&
(methodInfo.valueSetter || methodInfo.memberSetter) && methodInfo.pairedMethod != null) {
cast = cast(methodInfo.pairedMethod.getReturnType(), methodInfo.pairedMethod.getAnnotations());
}
return cast;
}
String cast(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
typeName = cppCastTypeName(type, annotations);
break;
}
}
return typeName != null && typeName.length > 0 ? "(" + typeName[0] + typeName[1] + ")" : "";
}
Annotation by(MethodInformation methodInfo, int j) {
Annotation passBy = by(methodInfo.parameterAnnotations[j]);
if (passBy == null && methodInfo.pairedMethod != null &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
passBy = by(methodInfo.pairedMethod.getAnnotations());
}
return passBy;
}
Annotation by(Annotation ... annotations) {
Annotation byAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof ByPtr || a instanceof ByPtrPtr || a instanceof ByPtrRef ||
a instanceof ByRef || a instanceof ByVal) {
if (byAnnotation != null) {
logger.warn("\"By\" annotation \"" + byAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
byAnnotation = a;
}
}
}
return byAnnotation;
}
Annotation behavior(Annotation ... annotations) {
Annotation behaviorAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof Function || a instanceof Allocator || a instanceof ArrayAllocator ||
a instanceof ValueSetter || a instanceof ValueGetter ||
a instanceof MemberGetter || a instanceof MemberSetter) {
if (behaviorAnnotation != null) {
logger.warn("Behavior annotation \"" + behaviorAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
behaviorAnnotation = a;
}
}
}
return behaviorAnnotation;
}
static String constValueTypeName(String ... typeName) {
String type = typeName[0];
if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
static String valueTypeName(String ... typeName) {
String type = typeName[0];
if (type.startsWith("const ")) {
type = type.substring(6, type.length()-1);
} else if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
String[] cppAnnotationTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = cppCastTypeName(type, annotations);
String prefix = typeName[0];
String suffix = typeName[1];
boolean casted = false;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
casted = true;
break;
}
}
Annotation by = by(annotations);
if (by instanceof ByVal) {
prefix = constValueTypeName(typeName);
} else if (by instanceof ByRef) {
prefix = constValueTypeName(typeName) + "&";
} else if (by instanceof ByPtrPtr && !casted) {
prefix = prefix + "*";
} else if (by instanceof ByPtrRef) {
prefix = prefix + "&";
} // else ByPtr
typeName[0] = prefix;
typeName[1] = suffix;
return typeName;
}
String[] cppCastTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
boolean warning = false, adapter = false;
for (Annotation a : annotations) {
if (a instanceof Cast) {
warning = typeName != null;
String prefix = ((Cast)a).value()[0], suffix = "";
int parenthesis = prefix.indexOf(')');
if (parenthesis > 0) {
suffix = prefix.substring(parenthesis).trim();
prefix = prefix.substring(0, parenthesis).trim();
}
typeName = prefix.length() > 0 ? new String[] { prefix, suffix } : null;
} else if (a instanceof Const) {
if (warning = typeName != null) {
// prioritize @Cast
continue;
}
typeName = cppTypeName(type);
boolean[] b = ((Const)a).value();
if (b.length > 1 && b[1]) {
typeName[0] = valueTypeName(typeName) + " const *";
}
if (b.length > 0 && b[0]) {
typeName[0] = "const " + typeName[0];
}
Annotation by = by(annotations);
if (by instanceof ByPtrPtr) {
typeName[0] += "*";
} else if (by instanceof ByPtrRef) {
typeName[0] += "&";
}
} else if (a instanceof Adapter || a.annotationType().isAnnotationPresent(Adapter.class)) {
adapter = true;
}
}
if (warning && !adapter) {
logger.warn("Without \"Adapter\", \"Cast\" and \"Const\" annotations are mutually exclusive.");
}
if (typeName == null) {
typeName = cppTypeName(type);
}
return typeName;
}
String[] cppTypeName(Class<?> type) {
String prefix = "", suffix = "";
if (type == Buffer.class || type == Pointer.class) {
prefix = "void*";
} else if (type == byte[].class || type == ByteBuffer.class || type == BytePointer.class) {
prefix = "signed char*";
} else if (type == short[].class || type == ShortBuffer.class || type == ShortPointer.class) {
prefix = "short*";
} else if (type == int[].class || type == IntBuffer.class || type == IntPointer.class) {
prefix = "int*";
} else if (type == long[].class || type == LongBuffer.class || type == LongPointer.class) {
prefix = "jlong*";
} else if (type == float[].class || type == FloatBuffer.class || type == FloatPointer.class) {
prefix = "float*";
} else if (type == double[].class || type == DoubleBuffer.class || type == DoublePointer.class) {
prefix = "double*";
} else if (type == char[].class || type == CharBuffer.class || type == CharPointer.class) {
prefix = "unsigned short*";
} else if (type == boolean[].class) {
prefix = "unsigned char*";
} else if (type == PointerPointer.class) {
prefix = "void**";
} else if (type == String.class) {
prefix = "const char*";
} else if (type == byte.class) {
prefix = "signed char";
} else if (type == long.class) {
prefix = "jlong";
} else if (type == char.class) {
prefix = "unsigned short";
} else if (type == boolean.class) {
prefix = "unsigned char";
} else if (type.isPrimitive()) {
prefix = type.getName();
} else if (FunctionPointer.class.isAssignableFrom(type)) {
Method functionMethod = functionMethod(type, null);
if (functionMethod != null) {
Convention convention = type.getAnnotation(Convention.class);
String callingConvention = convention == null ? "" : convention.value() + " ";
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
Class returnType = functionMethod.getReturnType();
Class[] parameterTypes = functionMethod.getParameterTypes();
Annotation[] annotations = functionMethod.getAnnotations();
Annotation[][] parameterAnnotations = functionMethod.getParameterAnnotations();
String[] returnTypeName = cppAnnotationTypeName(returnType, annotations);
AdapterInformation returnAdapterInfo = adapterInformation(false, valueTypeName(returnTypeName), annotations);
if (returnAdapterInfo != null && returnAdapterInfo.cast.length() > 0) {
prefix = returnAdapterInfo.cast;
} else {
prefix = returnTypeName[0] + returnTypeName[1];
}
prefix += " (" + callingConvention + spaceName + "*";
suffix = ")(";
if (namespace != null && !Pointer.class.isAssignableFrom(parameterTypes[0])) {
logger.warn("First parameter of caller method call() or apply() for member function pointer " +
type.getCanonicalName() + " is not a Pointer. Compilation will most likely fail.");
}
for (int j = namespace == null ? 0 : 1; j < parameterTypes.length; j++) {
String[] paramTypeName = cppAnnotationTypeName(parameterTypes[j], parameterAnnotations[j]);
AdapterInformation paramAdapterInfo = adapterInformation(false, valueTypeName(paramTypeName), parameterAnnotations[j]);
if (paramAdapterInfo != null && paramAdapterInfo.cast.length() > 0) {
suffix += paramAdapterInfo.cast + " arg" + j;
} else {
suffix += paramTypeName[0] + " arg" + j + paramTypeName[1];
}
if (j < parameterTypes.length - 1) {
suffix += ", ";
}
}
suffix += ")";
if (type.isAnnotationPresent(Const.class)) {
suffix += " const";
}
}
} else {
String scopedType = cppScopeName(type);
if (scopedType.length() > 0) {
prefix = scopedType + "*";
} else {
logger.warn("The class " + type.getCanonicalName() +
" does not map to any C++ type. Compilation will most likely fail.");
}
}
return new String[] { prefix, suffix };
}
static String cppScopeName(MethodInformation methodInfo) {
String scopeName = cppScopeName(methodInfo.cls);
Namespace namespace = methodInfo.method.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
scopeName = ""; // user wants to reset namespace here
}
if (scopeName.length() > 0 && !scopeName.endsWith("::")) {
scopeName += "::";
}
scopeName += spaceName;
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
scopeName += "::";
}
return scopeName + methodInfo.memberName[0];
}
static String cppScopeName(Class<?> type) {
String scopeName = "";
while (type != null) {
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (Pointer.class.isAssignableFrom(type) && type != Pointer.class) {
Name name = type.getAnnotation(Name.class);
String s;
if (name == null) {
s = type.getName();
int i = s.lastIndexOf("$");
if (i < 0) {
i = s.lastIndexOf(".");
}
s = s.substring(i+1);
} else {
s = name.value()[0];
}
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
spaceName += s;
}
if (scopeName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
scopeName = spaceName + scopeName;
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
// user wants to reset namespace here
break;
}
type = type.getDeclaringClass();
}
return scopeName;
}
static String jniTypeName(Class type) {
if (type == byte.class) {
return "jbyte";
} else if (type == short.class) {
return "jshort";
} else if (type == int.class) {
return "jint";
} else if (type == long.class) {
return "jlong";
} else if (type == float.class) {
return "jfloat";
} else if (type == double.class) {
return "jdouble";
} else if (type == char.class) {
return "jchar";
} else if (type == boolean.class) {
return "jboolean";
} else if (type == byte[].class) {
return "jbyteArray";
} else if (type == short[].class) {
return "jshortArray";
} else if (type == int[].class) {
return "jintArray";
} else if (type == long[].class) {
return "jlongArray";
} else if (type == float[].class) {
return "jfloatArray";
} else if (type == double[].class) {
return "jdoubleArray";
} else if (type == char[].class) {
return "jcharArray";
} else if (type == boolean[].class) {
return "jbooleanArray";
} else if (type.isArray()) {
return "jobjectArray";
} else if (type == String.class) {
return "jstring";
} else if (type == Class.class) {
return "jclass";
} else if (type == void.class) {
return "void";
} else {
return "jobject";
}
}
static String signature(Class ... types) {
StringBuilder signature = new StringBuilder(2*types.length);
for (Class type : types) {
if (type == byte.class) {
signature.append("B");
} else if (type == short.class) {
signature.append("S");
} else if (type == int.class) {
signature.append("I");
} else if (type == long.class) {
signature.append("J");
} else if (type == float.class) {
signature.append("F");
} else if (type == double.class) {
signature.append("D");
} else if (type == boolean.class) {
signature.append("Z");
} else if (type == char.class) {
signature.append("C");
} else if (type == void.class) {
signature.append("V");
} else if (type.isArray()) {
signature.append(type.getName().replace('.', '/'));
} else {
signature.append("L").append(type.getName().replace('.', '/')).append(";");
}
}
return signature.toString();
}
static String mangle(String name) {
StringBuilder mangledName = new StringBuilder(2*name.length());
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
mangledName.append(c);
} else if (c == '_') {
mangledName.append("_1");
} else if (c == ';') {
mangledName.append("_2");
} else if (c == '[') {
mangledName.append("_3");
} else if (c == '.' || c == '/') {
mangledName.append("_");
} else {
String code = Integer.toHexString(c);
mangledName.append("_0");
switch (code.length()) {
case 1: mangledName.append("0");
case 2: mangledName.append("0");
case 3: mangledName.append("0");
default: mangledName.append(code);
}
}
}
return mangledName.toString();
}
}
| tarzanking/javacpp | src/main/java/com/googlecode/javacpp/Generator.java | Java | gpl-2.0 | 138,100 |
/*
* Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.nodes;
import java.util.List;
import org.graalvm.compiler.graph.NodeClass;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* A {@link StructuredGraph} encoded in a compact binary representation as a byte[] array. See
* {@link GraphEncoder} for a description of the encoding format. Use {@link GraphDecoder} for
* decoding.
*/
public class EncodedGraph {
private final byte[] encoding;
private final long startOffset;
private final Object[] objects;
private final NodeClass<?>[] types;
private final Assumptions assumptions;
private final List<ResolvedJavaMethod> inlinedMethods;
/**
* The "table of contents" of the encoded graph, i.e., the mapping from orderId numbers to the
* offset in the encoded byte[] array. Used as a cache during decoding.
*/
protected long[] nodeStartOffsets;
public EncodedGraph(byte[] encoding, long startOffset, Object[] objects, NodeClass<?>[] types, Assumptions assumptions, List<ResolvedJavaMethod> inlinedMethods) {
this.encoding = encoding;
this.startOffset = startOffset;
this.objects = objects;
this.types = types;
this.assumptions = assumptions;
this.inlinedMethods = inlinedMethods;
}
public byte[] getEncoding() {
return encoding;
}
public long getStartOffset() {
return startOffset;
}
public Object[] getObjects() {
return objects;
}
public NodeClass<?>[] getNodeClasses() {
return types;
}
public Assumptions getAssumptions() {
return assumptions;
}
public List<ResolvedJavaMethod> getInlinedMethods() {
return inlinedMethods;
}
}
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/EncodedGraph.java | Java | gpl-2.0 | 2,807 |
/*
* Copyright 2006-2015 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.savitzkygolay;
public final class SGDerivative {
/**
* This method returns the second smoothed derivative values of an array.
*
* @param double[] values
* @param boolean is first derivative
* @param int level of filter (1 - 12)
* @return double[] derivative of values
*/
public static double[] calculateDerivative(double[] values,
boolean firstDerivative, int levelOfFilter) {
double[] derivative = new double[values.length];
int M = 0;
for (int k = 0; k < derivative.length; k++) {
// Determine boundaries
if (k <= levelOfFilter)
M = k;
if (k + M > derivative.length - 1)
M = derivative.length - (k + 1);
// Perform derivative using Savitzky Golay coefficients
for (int i = -M; i <= M; i++) {
derivative[k] += values[k + i]
* getSGCoefficient(M, i, firstDerivative);
}
// if ((Math.abs(derivative[k])) > maxValueDerivative)
// maxValueDerivative = Math.abs(derivative[k]);
}
return derivative;
}
/**
* This method return the Savitzky-Golay 2nd smoothed derivative coefficient
* from an array
*
* @param M
* @param signedC
* @return
*/
private static Double getSGCoefficient(int M, int signedC,
boolean firstDerivate) {
int C = Math.abs(signedC), sign = 1;
if (firstDerivate) {
if (signedC < 0)
sign = -1;
return sign
* SGCoefficients.SGCoefficientsFirstDerivativeQuartic[M][C];
} else {
return SGCoefficients.SGCoefficientsSecondDerivative[M][C];
}
}
}
| DrewG/mzmine2 | src/main/java/net/sf/mzmine/modules/peaklistmethods/peakpicking/deconvolution/savitzkygolay/SGDerivative.java | Java | gpl-2.0 | 2,508 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Yuri A. Kropachev
* @version $Revision$
*/
package org.apache.harmony.security.provider.crypto;
/**
* This interface contains : <BR>
* - a set of constant values, H0-H4, defined in "SECURE HASH STANDARD", FIPS PUB 180-2 ;<BR>
* - implementation constant values to use in classes using SHA-1 algorithm. <BR>
*/
public interface SHA1_Data {
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H0 = 0x67452301;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H1 = 0xEFCDAB89;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H2 = 0x98BADCFE;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H3 = 0x10325476;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H4 = 0xC3D2E1F0;
/**
* offset in buffer to store number of bytes in 0-15 word frame
*/
static final int BYTES_OFFSET = 81;
/**
* offset in buffer to store current hash value
*/
static final int HASH_OFFSET = 82;
/**
* # of bytes in H0-H4 words; <BR>
* in this implementation # is set to 20 (in general # varies from 1 to 20)
*/
static final int DIGEST_LENGTH = 20;
}
| xdajog/samsung_sources_i927 | libcore/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java | Java | gpl-2.0 | 2,129 |
package org.thoughtcrime.securesms.video;
import android.media.MediaDataSource;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import org.thoughtcrime.securesms.crypto.AttachmentSecret;
import org.thoughtcrime.securesms.crypto.ClassicDecryptingPartInputStream;
import org.thoughtcrime.securesms.util.Util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@RequiresApi(23)
final class ClassicEncryptedMediaDataSource extends MediaDataSource {
private final AttachmentSecret attachmentSecret;
private final File mediaFile;
private final long length;
ClassicEncryptedMediaDataSource(@NonNull AttachmentSecret attachmentSecret, @NonNull File mediaFile, long length) {
this.attachmentSecret = attachmentSecret;
this.mediaFile = mediaFile;
this.length = length;
}
@Override
public int readAt(long position, byte[] bytes, int offset, int length) throws IOException {
try (InputStream inputStream = ClassicDecryptingPartInputStream.createFor(attachmentSecret, mediaFile)) {
byte[] buffer = new byte[4096];
long headerRemaining = position;
while (headerRemaining > 0) {
int read = inputStream.read(buffer, 0, Util.toIntExact(Math.min((long)buffer.length, headerRemaining)));
if (read == -1) return -1;
headerRemaining -= read;
}
return inputStream.read(bytes, offset, length);
}
}
@Override
public long getSize() {
return length;
}
@Override
public void close() {}
}
| jtracey/Signal-Android | src/org/thoughtcrime/securesms/video/ClassicEncryptedMediaDataSource.java | Java | gpl-3.0 | 1,585 |
/*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.index.chain;
import java.util.*;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geomgraph.Quadrant;
/**
* Constructs {@link MonotoneChain}s
* for sequences of {@link Coordinate}s.
*
* @version 1.7
*/
public class MonotoneChainBuilder {
public static int[] toIntArray(List list)
{
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = ((Integer) list.get(i)).intValue();
}
return array;
}
public static List getChains(Coordinate[] pts)
{
return getChains(pts, null);
}
/**
* Return a list of the {@link MonotoneChain}s
* for the given list of coordinates.
*/
public static List getChains(Coordinate[] pts, Object context)
{
List mcList = new ArrayList();
int[] startIndex = getChainStartIndices(pts);
for (int i = 0; i < startIndex.length - 1; i++) {
MonotoneChain mc = new MonotoneChain(pts, startIndex[i], startIndex[i + 1], context);
mcList.add(mc);
}
return mcList;
}
/**
* Return an array containing lists of start/end indexes of the monotone chains
* for the given list of coordinates.
* The last entry in the array points to the end point of the point array,
* for use as a sentinel.
*/
public static int[] getChainStartIndices(Coordinate[] pts)
{
// find the startpoint (and endpoints) of all monotone chains in this edge
int start = 0;
List startIndexList = new ArrayList();
startIndexList.add(new Integer(start));
do {
int last = findChainEnd(pts, start);
startIndexList.add(new Integer(last));
start = last;
} while (start < pts.length - 1);
// copy list to an array of ints, for efficiency
int[] startIndex = toIntArray(startIndexList);
return startIndex;
}
/**
* Finds the index of the last point in a monotone chain
* starting at a given point.
* Any repeated points (0-length segments) will be included
* in the monotone chain returned.
*
* @return the index of the last point in the monotone chain
* starting at <code>start</code>.
*/
private static int findChainEnd(Coordinate[] pts, int start)
{
int safeStart = start;
// skip any zero-length segments at the start of the sequence
// (since they cannot be used to establish a quadrant)
while (safeStart < pts.length - 1 && pts[safeStart].equals2D(pts[safeStart + 1])) {
safeStart++;
}
// check if there are NO non-zero-length segments
if (safeStart >= pts.length - 1) {
return pts.length - 1;
}
// determine overall quadrant for chain (which is the starting quadrant)
int chainQuad = Quadrant.quadrant(pts[safeStart], pts[safeStart + 1]);
int last = start + 1;
while (last < pts.length) {
// skip zero-length segments, but include them in the chain
if (! pts[last - 1].equals2D(pts[last])) {
// compute quadrant for next possible segment in chain
int quad = Quadrant.quadrant(pts[last - 1], pts[last]);
if (quad != chainQuad) break;
}
last++;
}
return last - 1;
}
public MonotoneChainBuilder() {
}
}
| Jules-/terraingis | src/TerrainGIS/src/com/vividsolutions/jts/index/chain/MonotoneChainBuilder.java | Java | gpl-3.0 | 4,504 |
/**
* Aptana Studio
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.ui.io.navigator;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.Viewer;
import com.aptana.core.util.ArrayUtil;
import com.aptana.ide.core.io.CoreIOPlugin;
import com.aptana.ui.util.UIUtils;
public class ProjectExplorerContentProvider extends FileTreeContentProvider
{
private static final String LOCAL_SHORTCUTS_ID = "com.aptana.ide.core.io.localShortcuts"; //$NON-NLS-1$
private Viewer treeViewer;
private IResourceChangeListener resourceListener = new IResourceChangeListener()
{
public void resourceChanged(IResourceChangeEvent event)
{
// to fix https://jira.appcelerator.org/browse/TISTUD-1695, we need to force a selection update when a
// project is closed or opened
if (shouldUpdateActions(event.getDelta()))
{
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
treeViewer.setSelection(treeViewer.getSelection());
}
});
}
}
};
public ProjectExplorerContentProvider()
{
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
}
@Override
public void dispose()
{
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
super.dispose();
}
@Override
public Object[] getChildren(Object parentElement)
{
if (parentElement instanceof IResource)
{
return ArrayUtil.NO_OBJECTS;
}
return super.getChildren(parentElement);
}
@Override
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof IWorkspaceRoot)
{
List<Object> children = new ArrayList<Object>();
children.add(LocalFileSystems.getInstance());
children.add(CoreIOPlugin.getConnectionPointManager().getConnectionPointCategory(LOCAL_SHORTCUTS_ID));
return children.toArray(new Object[children.size()]);
}
return super.getElements(inputElement);
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
treeViewer = viewer;
super.inputChanged(viewer, oldInput, newInput);
}
private boolean shouldUpdateActions(IResourceDelta delta)
{
if (delta.getFlags() == IResourceDelta.OPEN)
{
return true;
}
IResourceDelta[] children = delta.getAffectedChildren();
for (IResourceDelta child : children)
{
if (shouldUpdateActions(child))
{
return true;
}
}
return false;
}
}
| HossainKhademian/Studio3 | plugins/com.aptana.ui.io/src/com/aptana/ide/ui/io/navigator/ProjectExplorerContentProvider.java | Java | gpl-3.0 | 3,028 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.groovy;
import static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.GroovyObjectSupport;
import java.util.NavigableMap;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import com.google_voltpatches.common.collect.ImmutableSortedMap;
/**
* Groovy table access expediter. It allows you to easily navigate a VoltTable,
* and access its column values.
* <p>
* Example usage on a query that returns results for the :
* <code><pre>
* cr = client.callProcedure('@AdHoc','select INTEGER_COL, STRING_COL from FOO')
* tuplerator(cr.results[0]).eachRow {
*
* integerColValueByIndex = it[0]
* stringColValueByIndex = it[1]
*
* integerColValueByName = it['integerCol']
* stringColValyeByName = it['stringCol']
*
* integerColValueByField = it.integerCol
* stringColValyeByField = it.stringCol
* }
*
* </code></pre>
*
*/
public class Tuplerator extends GroovyObjectSupport {
private final VoltTable table;
private final VoltType [] byIndex;
private final NavigableMap<String, Integer> byName;
public static Tuplerator newInstance(VoltTable table) {
return new Tuplerator(table);
}
public Tuplerator(final VoltTable table) {
this.table = table;
this.byIndex = new VoltType[table.getColumnCount()];
ImmutableSortedMap.Builder<String, Integer> byNameBuilder =
ImmutableSortedMap.naturalOrder();
for (int c = 0; c < byIndex.length; ++c) {
VoltType cType = table.getColumnType(c);
StringBuilder cName = new StringBuilder(table.getColumnName(c));
byIndex[c] = cType;
boolean upperCaseIt = false;
for (int i = 0; i < cName.length();) {
char chr = cName.charAt(i);
if (chr == '_' || chr == '.' || chr == '$') {
cName.deleteCharAt(i);
upperCaseIt = true;
} else {
chr = upperCaseIt ? toUpperCase(chr) : toLowerCase(chr);
cName.setCharAt(i, chr);
upperCaseIt = false;
++i;
}
}
byNameBuilder.put(cName.toString(),c);
}
byName = byNameBuilder.build();
}
/**
* It calls the given closure on each row of the underlying table by passing itself
* as the only closure parameter
*
* @param c the self instance of Tuplerator
*/
public void eachRow(Closure<Void> c) {
while (table.advanceRow()) {
c.call(this);
}
table.resetRowPosition();
}
/**
* It calls the given closure on each row of the underlying table for up to the specified limit,
* by passing itself as the only closure parameter
*
* @param maxRows maximum rows to call the closure on
* @param c closure
*/
public void eachRow(int maxRows, Closure<Void> c) {
while (--maxRows >= 0 && table.advanceRow()) {
c.call(this);
}
}
public Object getAt(int cidx) {
Object cval = table.get(cidx, byIndex[cidx]);
if (table.wasNull()) cval = null;
return cval;
}
public Object getAt(String cname) {
Integer cidx = byName.get(cname);
if (cidx == null) {
throw new IllegalArgumentException("No Column named '" + cname + "'");
}
return getAt(cidx);
}
public Object getAt(GString cname) {
return getAt(cname.toString());
}
@Override
public Object getProperty(String name) {
return getAt(name);
}
/**
* Sets the table row cursor to the given position
* @param num row number to set the row cursor to
* @return an instance of self
*/
public Tuplerator atRow(int num) {
table.advanceToRow(num);
return this;
}
/**
* Resets the table row cursor
* @return an instance of self
*/
public Tuplerator reset() {
table.resetRowPosition();
return this;
}
/**
* Returns the underlying table
* @return the underlying table
*/
public VoltTable getTable() {
return table;
}
}
| wolffcm/voltdb | src/frontend/org/voltdb/groovy/Tuplerator.java | Java | agpl-3.0 | 5,058 |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.driver.internal.behavior.handler.codec.http;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.US_ASCII;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.ConfigEncoder;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.MessageEncoder;
import org.kaazing.k3po.driver.internal.netty.bootstrap.http.HttpChannelConfig;
public class HttpStatusEncoder implements ConfigEncoder {
private final MessageEncoder codeEncoder;
private final MessageEncoder reasonEncoder;
public HttpStatusEncoder(MessageEncoder codeEncoder, MessageEncoder reasonEncoder) {
this.codeEncoder = codeEncoder;
this.reasonEncoder = reasonEncoder;
}
@Override
public void encode(Channel channel) throws Exception {
HttpChannelConfig httpConfig = (HttpChannelConfig) channel.getConfig();
int code = Integer.parseInt(codeEncoder.encode().toString(US_ASCII));
String reason = reasonEncoder.encode().toString(US_ASCII);
HttpResponseStatus status = new HttpResponseStatus(code, reason);
httpConfig.setStatus(status);
}
@Override
public String toString() {
return format("http:status %s %s", codeEncoder, reasonEncoder);
}
}
| mgherghe/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/http/HttpStatusEncoder.java | Java | agpl-3.0 | 2,014 |
package dr.app.beauti.types;
/**
* @author Marc A. Suchard
*/
public enum HierarchicalModelType {
NORMAL_HPM,
LOGNORMAL_HPM;
public String toString() {
switch (this) {
case NORMAL_HPM:
return "Normal";
case LOGNORMAL_HPM:
return "Lognormal";
default:
return "";
}
}
}
| evolvedmicrobe/beast-mcmc | src/dr/app/beauti/types/HierarchicalModelType.java | Java | lgpl-2.1 | 406 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.jobrunning.crawler;
public class JobContext {
public String jobId;
public String user;
public Long fetchedTime;
public JobContext() {
}
public JobContext(JobContext context) {
this.jobId = new String(context.jobId);
this.user = new String(context.user);
this.fetchedTime = new Long(context.fetchedTime);
}
public JobContext(String jobId, String user, Long fetchedTime) {
this.jobId = jobId;
this.user = user;
this.fetchedTime = fetchedTime;
}
@Override
public int hashCode() {
return jobId.hashCode() ;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JobContext) {
JobContext context = (JobContext)obj;
if (this.jobId.equals(context.jobId)) {
return true;
}
}
return false;
}
}
| eBay/Eagle | eagle-core/eagle-data-process/eagle-storm-jobrunning-spout/src/main/java/org/apache/eagle/jobrunning/crawler/JobContext.java | Java | apache-2.0 | 1,589 |
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java;
import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING;
import com.facebook.buck.io.DirectoryTraverser;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirAndSymlinkFileStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.Nullable;
@BuildsAnnotationProcessor
public class JavaBinary extends AbstractBuildRule
implements BinaryBuildRule, HasClasspathEntries, RuleKeyAppendable {
private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING);
@AddToRuleKey
@Nullable
private final String mainClass;
@AddToRuleKey
@Nullable
private final SourcePath manifestFile;
private final boolean mergeManifests;
@Nullable
private final Path metaInfDirectory;
@AddToRuleKey
private final ImmutableSet<String> blacklist;
private final DirectoryTraverser directoryTraverser;
private final ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries;
public JavaBinary(
BuildRuleParams params,
SourcePathResolver resolver,
@Nullable String mainClass,
@Nullable SourcePath manifestFile,
boolean mergeManifests,
@Nullable Path metaInfDirectory,
ImmutableSet<String> blacklist,
DirectoryTraverser directoryTraverser,
ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries) {
super(params, resolver);
this.mainClass = mainClass;
this.manifestFile = manifestFile;
this.mergeManifests = mergeManifests;
this.metaInfDirectory = metaInfDirectory;
this.blacklist = blacklist;
this.directoryTraverser = directoryTraverser;
this.transitiveClasspathEntries = transitiveClasspathEntries;
}
@Override
public BuildableProperties getProperties() {
return OUTPUT_TYPE;
}
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
// Build a sorted set so that metaInfDirectory contents are listed in a canonical order.
ImmutableSortedSet.Builder<Path> paths = ImmutableSortedSet.naturalOrder();
BuildRules.addInputsToSortedSet(metaInfDirectory, paths, directoryTraverser);
return builder.setReflectively(
"metaInfDirectory",
FluentIterable.from(paths.build())
.transform(SourcePaths.toSourcePath(getProjectFilesystem())));
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
ImmutableList.Builder<Step> commands = ImmutableList.builder();
Path outputDirectory = getOutputDirectory();
Step mkdir = new MkdirStep(getProjectFilesystem(), outputDirectory);
commands.add(mkdir);
ImmutableSortedSet<Path> includePaths;
if (metaInfDirectory != null) {
Path stagingRoot = outputDirectory.resolve("meta_inf_staging");
Path stagingTarget = stagingRoot.resolve("META-INF");
MakeCleanDirectoryStep createStagingRoot = new MakeCleanDirectoryStep(
getProjectFilesystem(),
stagingRoot);
commands.add(createStagingRoot);
MkdirAndSymlinkFileStep link = new MkdirAndSymlinkFileStep(
getProjectFilesystem(),
metaInfDirectory,
stagingTarget);
commands.add(link);
includePaths = ImmutableSortedSet.<Path>naturalOrder()
.add(stagingRoot)
.addAll(getTransitiveClasspathEntries().values())
.build();
} else {
includePaths = ImmutableSortedSet.copyOf(getTransitiveClasspathEntries().values());
}
Path outputFile = getPathToOutput();
Path manifestPath = manifestFile == null ? null : getResolver().getAbsolutePath(manifestFile);
Step jar = new JarDirectoryStep(
getProjectFilesystem(),
outputFile,
includePaths,
mainClass,
manifestPath,
mergeManifests,
blacklist);
commands.add(jar);
buildableContext.recordArtifact(outputFile);
return commands.build();
}
@Override
public ImmutableSetMultimap<JavaLibrary, Path> getTransitiveClasspathEntries() {
return transitiveClasspathEntries;
}
@Override
public ImmutableSet<JavaLibrary> getTransitiveClasspathDeps() {
return transitiveClasspathEntries.keySet();
}
private Path getOutputDirectory() {
return BuildTargets.getGenPath(getBuildTarget(), "%s").getParent();
}
@Override
public Path getPathToOutput() {
return Paths.get(
String.format(
"%s/%s.jar",
getOutputDirectory(),
getBuildTarget().getShortNameAndFlavorPostfix()));
}
@Override
public Tool getExecutableCommand() {
Preconditions.checkState(
mainClass != null,
"Must specify a main class for %s in order to to run it.",
getBuildTarget());
return new CommandTool.Builder()
.addArg("java")
.addArg("-jar")
.addArg(new BuildTargetSourcePath(getBuildTarget()))
.build();
}
}
| mikekap/buck | src/com/facebook/buck/jvm/java/JavaBinary.java | Java | apache-2.0 | 6,767 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gobblin.runtime.commit;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import gobblin.commit.CommitSequence;
import gobblin.commit.FsRenameCommitStep;
import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.State;
import gobblin.runtime.JobState.DatasetState;
/**
* Tests for {@link CommitSequence}.
*
* @author Ziyang Liu
*/
@Test(groups = { "gobblin.runtime.commit" })
public class CommitSequenceTest {
private static final String ROOT_DIR = "commit-sequence-test";
private FileSystem fs;
private CommitSequence sequence;
@BeforeClass
public void setUp() throws IOException {
this.fs = FileSystem.getLocal(new Configuration());
this.fs.delete(new Path(ROOT_DIR), true);
Path storeRootDir = new Path(ROOT_DIR, "store");
Path dir1 = new Path(ROOT_DIR, "dir1");
Path dir2 = new Path(ROOT_DIR, "dir2");
this.fs.mkdirs(dir1);
this.fs.mkdirs(dir2);
Path src1 = new Path(dir1, "file1");
Path src2 = new Path(dir2, "file2");
Path dst1 = new Path(dir2, "file1");
Path dst2 = new Path(dir1, "file2");
this.fs.createNewFile(src1);
this.fs.createNewFile(src2);
DatasetState ds = new DatasetState("job-name", "job-id");
ds.setDatasetUrn("urn");
ds.setNoJobFailure();
State state = new State();
state.setProp(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, storeRootDir.toString());
this.sequence = new CommitSequence.Builder().withJobName("testjob").withDatasetUrn("testurn")
.beginStep(FsRenameCommitStep.Builder.class).from(src1).to(dst1).withProps(state).endStep()
.beginStep(FsRenameCommitStep.Builder.class).from(src2).to(dst2).withProps(state).endStep()
.beginStep(DatasetStateCommitStep.Builder.class).withDatasetUrn("urn").withDatasetState(ds).withProps(state)
.endStep().build();
}
@AfterClass
public void tearDown() throws IOException {
this.fs.delete(new Path(ROOT_DIR), true);
}
@Test
public void testExecute() throws IOException {
this.sequence.execute();
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir1/file2")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir2/file1")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-job-id.jst")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-current.jst")));
}
}
| ydai1124/gobblin-1 | gobblin-runtime/src/test/java/gobblin/runtime/commit/CommitSequenceTest.java | Java | apache-2.0 | 3,431 |
/*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.bayesian.network.client.factory;
import com.ait.lienzo.client.core.shape.Rectangle;
import com.ait.lienzo.client.core.shape.Shape;
import com.ait.lienzo.client.core.shape.Text;
import com.ait.lienzo.shared.core.types.Color;
import org.uberfire.ext.wires.core.client.util.ShapesUtils;
public class BaseFactory {
private static final String defaultFillColor = ShapesUtils.RGB_FILL_SHAPE;
private static final String defaultBorderColor = ShapesUtils.RGB_STROKE_SHAPE;
protected void setAttributes( final Shape<?> shape,
final String fillColor,
final double x,
final double y,
final String borderColor ) {
String fill = ( fillColor == null ) ? defaultFillColor : fillColor;
String border = ( borderColor == null ) ? defaultBorderColor : borderColor;
shape.setX( x ).setY( y ).setStrokeColor( border ).setStrokeWidth( ShapesUtils.RGB_STROKE_WIDTH_SHAPE ).setFillColor( fill ).setDraggable( false );
}
protected Rectangle drawComponent( final String color,
final int positionX,
final int positionY,
final int width,
final int height,
String borderColor,
double radius ) {
if ( borderColor == null ) {
borderColor = Color.rgbToBrowserHexColor( 0, 0, 0 );
}
Rectangle component = new Rectangle( width,
height );
setAttributes( component,
color,
positionX,
positionY,
borderColor );
component.setCornerRadius( radius );
return component;
}
protected Text drawText( final String description,
final int fontSize,
final int positionX,
final int positionY ) {
return new Text( description,
"Times",
fontSize ).setX( positionX ).setY( positionY );
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bayesian-network/uberfire-wires-bayesian-network-client/src/main/java/org/uberfire/ext/wires/bayesian/network/client/factory/BaseFactory.java | Java | apache-2.0 | 2,954 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupActionProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementAction;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.util.Consumer;
import com.intellij.util.PlatformIcons;
/**
* @author peter
*/
public class LiveTemplateLookupActionProvider implements LookupActionProvider {
@Override
public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
if (element instanceof LiveTemplateLookupElementImpl) {
final TemplateImpl template = ((LiveTemplateLookupElementImpl)element).getTemplate();
final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName());
if (templateFromSettings != null) {
consumer.consume(new LookupElementAction(PlatformIcons.EDIT, CodeInsightBundle.message("action.text.edit.live.template.settings")) {
@Override
public Result performLookupAction() {
final Project project = lookup.getProject();
ApplicationManager.getApplication().invokeLater(() -> {
if (project.isDisposed()) return;
final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().editTemplate(template));
});
return Result.HIDE_LOOKUP;
}
});
consumer.consume(new LookupElementAction(AllIcons.Actions.Cancel, CodeInsightBundle.message("action.text.disable.live.template", template.getKey())) {
@Override
public Result performLookupAction() {
ApplicationManager.getApplication().invokeLater(() -> templateFromSettings.setDeactivated(true));
return Result.HIDE_LOOKUP;
}
});
}
}
}
}
| siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java | Java | apache-2.0 | 2,424 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.connect.file;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.utils.AppInfoParser;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.sink.SinkConnector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Very simple connector that works with the console. This connector supports both source and
* sink modes via its 'mode' setting.
*/
public class FileStreamSinkConnector extends SinkConnector {
public static final String FILE_CONFIG = "file";
private static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(FILE_CONFIG, Type.STRING, Importance.HIGH, "Destination filename.");
private String filename;
@Override
public String version() {
return AppInfoParser.getVersion();
}
@Override
public void start(Map<String, String> props) {
filename = props.get(FILE_CONFIG);
}
@Override
public Class<? extends Task> taskClass() {
return FileStreamSinkTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
ArrayList<Map<String, String>> configs = new ArrayList<>();
for (int i = 0; i < maxTasks; i++) {
Map<String, String> config = new HashMap<>();
if (filename != null)
config.put(FILE_CONFIG, filename);
configs.add(config);
}
return configs;
}
@Override
public void stop() {
// Nothing to do since FileStreamSinkConnector has no background monitoring.
}
@Override
public ConfigDef config() {
return CONFIG_DEF;
}
}
| wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/file/src/main/java/org/apache/kafka/connect/file/FileStreamSinkConnector.java | Java | apache-2.0 | 2,629 |
package org.python.util.install.driver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.python.util.install.ChildProcess;
import org.python.util.install.FileHelper;
public class NormalVerifier implements Verifier {
protected static final String AUTOTEST_PY = "autotest.py";
private static final String BIN = "bin";
private static final String JYTHON_UP = "jython up and running!";
private static final String JYTHON = "jython";
private static final String VERIFYING = "verifying";
private File _targetDir;
public void setTargetDir(File targetDir) {
_targetDir = targetDir;
}
public File getTargetDir() {
return _targetDir;
}
public void verify() throws DriverException {
createTestScriptFile(); // create the test .py script
// verify the most simple start of jython works
verifyStart(getSimpleCommand());
}
/**
* Will be overridden in subclass StandaloneVerifier
*
* @return the command array to start jython with
* @throws DriverException
* if there was a problem getting the target directory path
*/
protected String[] getSimpleCommand() throws DriverException {
return new String[] {
Paths.get(BIN).resolve(JYTHON).toString(),
_targetDir.toPath().resolve(AUTOTEST_PY).toString() };
}
/**
* @return The directory where to create the shell script test command in.
*
* @throws DriverException
*/
protected final File getShellScriptTestCommandDir() throws DriverException {
return _targetDir.toPath().resolve(BIN).toFile();
}
/**
* Internal method verifying a jython-starting command by capturing the output
*
* @param command
*
* @throws DriverException
*/
private void verifyStart(String[] command) throws DriverException {
ChildProcess p = new ChildProcess(command);
p.setDebug(true);
p.setCWD(_targetDir.toPath());
System.err.println("Verify start: command=" + Arrays.toString(command) + ", cwd=" + p.getCWD());
int exitValue = p.run();
// if (exitValue != 0) {
// throw new DriverException("start of jython failed\n"
// + "command: " + Arrays.toString(command)
// + "\ncwd: " + p.getCWD()
// + "\nexit value: " + exitValue
// + "\nstdout: " + p.getStdout()
// + "\nstderr: " + p.getStderr());
// }
verifyError(p.getStderr());
verifyOutput(p.getStdout());
}
/**
* Will be overridden in subclass StandaloneVerifier
*
* @return <code>true</code> if the jython start shell script should be verified (using
* different options)
*/
protected boolean doShellScriptTests() {
return true;
}
private void verifyError(List<String> stderr) throws DriverException {
for (String line : stderr) {
if (isExpectedError(line)) {
feedback(line);
} else {
throw new DriverException(stderr.toString());
}
}
}
private boolean isExpectedError(String line) {
boolean expected = false;
if (line.startsWith("*sys-package-mgr*")) {
expected = true;
}
return expected;
}
private void verifyOutput(List<String> stdout) throws DriverException {
boolean started = false;
for (String line : stdout) {
if (isExpectedOutput(line)) {
feedback(line);
if (line.startsWith(JYTHON_UP)) {
started = true;
}
} else {
throw new DriverException(stdout.toString());
}
}
if (!started) {
throw new DriverException("start of jython failed:\n" + stdout.toString());
}
}
private boolean isExpectedOutput(String line) {
boolean expected = false;
if (line.startsWith("[ChildProcess]") || line.startsWith(VERIFYING)) {
expected = true;
} else if (line.startsWith(JYTHON_UP)) {
expected = true;
}
return expected;
}
private String getTestScript() {
StringBuilder b = new StringBuilder(80);
b.append("import sys\n");
b.append("import os\n");
b.append("print '");
b.append(JYTHON_UP);
b.append("'\n");
return b.toString();
}
private void createTestScriptFile() throws DriverException {
File file = new File(getTargetDir(), AUTOTEST_PY);
try {
FileHelper.write(file, getTestScript());
} catch (IOException ioe) {
throw new DriverException(ioe);
}
}
private void feedback(String line) {
System.out.println("feedback " + line);
}
}
| alvin319/CarnotKE | jyhton/installer/src/java/org/python/util/install/driver/NormalVerifier.java | Java | apache-2.0 | 5,129 |
/*
* WSO2 API Manager - Publisher API
* This specifies a **RESTful API** for WSO2 **API Manager** - Publisher. Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.0.4/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/resources/publisher-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification.
*
* OpenAPI spec version: v1.0.0
* Contact: architecture@wso2.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.wso2.carbon.apimgt.rest.integration.tests.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
/**
* CORS configuration for the API
*/
@ApiModel(description = "CORS configuration for the API ")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-05-09T06:36:48.873Z")
public class APICorsConfiguration {
@SerializedName("corsConfigurationEnabled")
private Boolean corsConfigurationEnabled = false;
@SerializedName("accessControlAllowOrigins")
private List<String> accessControlAllowOrigins = new ArrayList<String>();
@SerializedName("accessControlAllowCredentials")
private Boolean accessControlAllowCredentials = false;
@SerializedName("accessControlAllowHeaders")
private List<String> accessControlAllowHeaders = new ArrayList<String>();
@SerializedName("accessControlAllowMethods")
private List<String> accessControlAllowMethods = new ArrayList<String>();
public APICorsConfiguration corsConfigurationEnabled(Boolean corsConfigurationEnabled) {
this.corsConfigurationEnabled = corsConfigurationEnabled;
return this;
}
/**
* Get corsConfigurationEnabled
* @return corsConfigurationEnabled
**/
@ApiModelProperty(example = "null", value = "")
public Boolean getCorsConfigurationEnabled() {
return corsConfigurationEnabled;
}
public void setCorsConfigurationEnabled(Boolean corsConfigurationEnabled) {
this.corsConfigurationEnabled = corsConfigurationEnabled;
}
public APICorsConfiguration accessControlAllowOrigins(List<String> accessControlAllowOrigins) {
this.accessControlAllowOrigins = accessControlAllowOrigins;
return this;
}
public APICorsConfiguration addAccessControlAllowOriginsItem(String accessControlAllowOriginsItem) {
this.accessControlAllowOrigins.add(accessControlAllowOriginsItem);
return this;
}
/**
* Get accessControlAllowOrigins
* @return accessControlAllowOrigins
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowOrigins() {
return accessControlAllowOrigins;
}
public void setAccessControlAllowOrigins(List<String> accessControlAllowOrigins) {
this.accessControlAllowOrigins = accessControlAllowOrigins;
}
public APICorsConfiguration accessControlAllowCredentials(Boolean accessControlAllowCredentials) {
this.accessControlAllowCredentials = accessControlAllowCredentials;
return this;
}
/**
* Get accessControlAllowCredentials
* @return accessControlAllowCredentials
**/
@ApiModelProperty(example = "null", value = "")
public Boolean getAccessControlAllowCredentials() {
return accessControlAllowCredentials;
}
public void setAccessControlAllowCredentials(Boolean accessControlAllowCredentials) {
this.accessControlAllowCredentials = accessControlAllowCredentials;
}
public APICorsConfiguration accessControlAllowHeaders(List<String> accessControlAllowHeaders) {
this.accessControlAllowHeaders = accessControlAllowHeaders;
return this;
}
public APICorsConfiguration addAccessControlAllowHeadersItem(String accessControlAllowHeadersItem) {
this.accessControlAllowHeaders.add(accessControlAllowHeadersItem);
return this;
}
/**
* Get accessControlAllowHeaders
* @return accessControlAllowHeaders
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowHeaders() {
return accessControlAllowHeaders;
}
public void setAccessControlAllowHeaders(List<String> accessControlAllowHeaders) {
this.accessControlAllowHeaders = accessControlAllowHeaders;
}
public APICorsConfiguration accessControlAllowMethods(List<String> accessControlAllowMethods) {
this.accessControlAllowMethods = accessControlAllowMethods;
return this;
}
public APICorsConfiguration addAccessControlAllowMethodsItem(String accessControlAllowMethodsItem) {
this.accessControlAllowMethods.add(accessControlAllowMethodsItem);
return this;
}
/**
* Get accessControlAllowMethods
* @return accessControlAllowMethods
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowMethods() {
return accessControlAllowMethods;
}
public void setAccessControlAllowMethods(List<String> accessControlAllowMethods) {
this.accessControlAllowMethods = accessControlAllowMethods;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
APICorsConfiguration apICorsConfiguration = (APICorsConfiguration) o;
return Objects.equals(this.corsConfigurationEnabled, apICorsConfiguration.corsConfigurationEnabled) &&
Objects.equals(this.accessControlAllowOrigins, apICorsConfiguration.accessControlAllowOrigins) &&
Objects.equals(this.accessControlAllowCredentials, apICorsConfiguration.accessControlAllowCredentials) &&
Objects.equals(this.accessControlAllowHeaders, apICorsConfiguration.accessControlAllowHeaders) &&
Objects.equals(this.accessControlAllowMethods, apICorsConfiguration.accessControlAllowMethods);
}
@Override
public int hashCode() {
return Objects.hash(corsConfigurationEnabled, accessControlAllowOrigins, accessControlAllowCredentials, accessControlAllowHeaders, accessControlAllowMethods);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class APICorsConfiguration {\n");
sb.append(" corsConfigurationEnabled: ").append(toIndentedString(corsConfigurationEnabled)).append("\n");
sb.append(" accessControlAllowOrigins: ").append(toIndentedString(accessControlAllowOrigins)).append("\n");
sb.append(" accessControlAllowCredentials: ").append(toIndentedString(accessControlAllowCredentials)).append("\n");
sb.append(" accessControlAllowHeaders: ").append(toIndentedString(accessControlAllowHeaders)).append("\n");
sb.append(" accessControlAllowMethods: ").append(toIndentedString(accessControlAllowMethods)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| abimarank/product-apim | integration-tests/src/main/java/org/wso2/carbon/apimgt/rest/integration/tests/model/APICorsConfiguration.java | Java | apache-2.0 | 7,272 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.impl.engine;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.Validator;
import org.apache.camel.spi.ValidatorRegistry;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.ObjectHelper;
/**
* Default implementation of {@link org.apache.camel.spi.ValidatorRegistry}.
*/
public class DefaultValidatorRegistry extends AbstractDynamicRegistry<ValidatorKey, Validator>
implements ValidatorRegistry<ValidatorKey> {
public DefaultValidatorRegistry(CamelContext context) {
super(context, CamelContextHelper.getMaximumValidatorCacheSize(context));
}
@Override
public Validator resolveValidator(ValidatorKey key) {
Validator answer = get(key);
if (answer == null && ObjectHelper.isNotEmpty(key.getType().getName())) {
answer = get(new ValidatorKey(new DataType(key.getType().getModel())));
}
return answer;
}
@Override
public boolean isStatic(DataType type) {
return isStatic(new ValidatorKey(type));
}
@Override
public boolean isDynamic(DataType type) {
return isDynamic(new ValidatorKey(type));
}
@Override
public String toString() {
return "ValidatorRegistry for " + context.getName() + " [capacity: " + maxCacheSize + "]";
}
@Override
public Validator put(ValidatorKey key, Validator obj) {
// ensure validator is started before its being used
ServiceHelper.startService(obj);
return super.put(key, obj);
}
}
| nikhilvibhav/camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultValidatorRegistry.java | Java | apache-2.0 | 2,457 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.protocol.ftp;
import java.net.URL;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRulesParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.SimpleRobotRules;
/**
* This class is used for parsing robots for urls belonging to FTP protocol.
* It extends the generic {@link RobotRulesParser} class and contains
* Ftp protocol specific implementation for obtaining the robots file.
*/
public class FtpRobotRulesParser extends RobotRulesParser {
private static final String CONTENT_TYPE = "text/plain";
public static final Logger LOG = LoggerFactory.getLogger(FtpRobotRulesParser.class);
FtpRobotRulesParser() { }
public FtpRobotRulesParser(Configuration conf) {
super(conf);
}
/**
* The hosts for which the caching of robots rules is yet to be done,
* it sends a Ftp request to the host corresponding to the {@link URL}
* passed, gets robots file, parses the rules and caches the rules object
* to avoid re-work in future.
*
* @param ftp The {@link Protocol} object
* @param url URL
*
* @return robotRules A {@link BaseRobotRules} object for the rules
*/
public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url) {
String protocol = url.getProtocol().toLowerCase(); // normalize to lower case
String host = url.getHost().toLowerCase(); // normalize to lower case
BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":" + host);
boolean cacheRule = true;
if (robotRules == null) { // cache miss
if (LOG.isTraceEnabled())
LOG.trace("cache miss " + url);
try {
Text robotsUrl = new Text(new URL(url, "/robots.txt").toString());
ProtocolOutput output = ((Ftp)ftp).getProtocolOutput(robotsUrl, new CrawlDatum());
ProtocolStatus status = output.getStatus();
if (status.getCode() == ProtocolStatus.SUCCESS) {
robotRules = parseRules(url.toString(), output.getContent().getContent(),
CONTENT_TYPE, agentNames);
} else {
robotRules = EMPTY_RULES; // use default rules
}
} catch (Throwable t) {
if (LOG.isInfoEnabled()) {
LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
}
cacheRule = false;
robotRules = EMPTY_RULES;
}
if (cacheRule)
CACHE.put(protocol + ":" + host, robotRules); // cache rules for host
}
return robotRules;
}
}
| fogbeam/Heceta_nutch | src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java | Java | apache-2.0 | 3,708 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.spi.systemview.view;
import org.apache.ignite.internal.managers.systemview.walker.Order;
import org.apache.ignite.internal.processors.query.QueryUtils;
import org.apache.ignite.internal.processors.query.h2.sys.view.SqlSystemView;
/**
* Sql view representation for a {@link SystemView}.
*/
public class SqlViewView {
/** Sql system view. */
private final SqlSystemView view;
/** @param view Sql system view. */
public SqlViewView(SqlSystemView view) {
this.view = view;
}
/** View name. */
@Order
public String name() {
return view.getTableName();
}
/** View description. */
@Order(2)
public String description() {
return view.getDescription();
}
/** View schema. */
@Order(1)
public String schema() {
return QueryUtils.SCHEMA_SYS;
}
}
| samaitra/ignite | modules/indexing/src/main/java/org/apache/ignite/spi/systemview/view/SqlViewView.java | Java | apache-2.0 | 1,673 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.protocols.ssl;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.Option;
import org.xnio.Options;
import io.undertow.connector.ByteBufferPool;
import org.xnio.SslClientAuthMode;
import org.xnio.StreamConnection;
import org.xnio.ssl.SslConnection;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.Executor;
/**
* @author Stuart Douglas
*/
class UndertowSslConnection extends SslConnection {
private static final Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder().add(Options.SECURE, Options.SSL_CLIENT_AUTH_MODE).create();
private final StreamConnection delegate;
private final SslConduit sslConduit;
private final ChannelListener.SimpleSetter<SslConnection> handshakeSetter = new ChannelListener.SimpleSetter<>();
private final SSLEngine engine;
/**
* Construct a new instance.
*
* @param delegate the underlying connection
*/
UndertowSslConnection(StreamConnection delegate, SSLEngine engine, ByteBufferPool bufferPool, Executor delegatedTaskExecutor) {
super(delegate.getIoThread());
this.delegate = delegate;
this.engine = engine;
sslConduit = new SslConduit(this, delegate, engine, delegatedTaskExecutor, bufferPool, new HandshakeCallback());
setSourceConduit(sslConduit);
setSinkConduit(sslConduit);
}
@Override
public void startHandshake() throws IOException {
sslConduit.startHandshake();
}
@Override
public SSLSession getSslSession() {
return sslConduit.getSslSession();
}
@Override
public ChannelListener.Setter<? extends SslConnection> getHandshakeSetter() {
return handshakeSetter;
}
@Override
protected void notifyWriteClosed() {
sslConduit.notifyWriteClosed();
}
@Override
protected void notifyReadClosed() {
sslConduit.notifyReadClosed();
}
@Override
public SocketAddress getPeerAddress() {
return delegate.getPeerAddress();
}
@Override
public SocketAddress getLocalAddress() {
return delegate.getLocalAddress();
}
public SSLEngine getSSLEngine() {
return sslConduit.getSSLEngine();
}
SslConduit getSslConduit() {
return sslConduit;
}
/** {@inheritDoc} */
@Override
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
try {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} finally {
engine.setWantClientAuth(false);
engine.setNeedClientAuth(false);
if (value == SslClientAuthMode.REQUESTED) {
engine.setWantClientAuth(true);
} else if (value == SslClientAuthMode.REQUIRED) {
engine.setNeedClientAuth(true);
}
}
} else if (option == Options.SECURE) {
throw new IllegalArgumentException();
} else {
return delegate.setOption(option, value);
}
}
/** {@inheritDoc} */
@Override
public <T> T getOption(final Option<T> option) throws IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} else {
return option == Options.SECURE ? (T)Boolean.TRUE : delegate.getOption(option);
}
}
/** {@inheritDoc} */
@Override
public boolean supportsOption(final Option<?> option) {
return SUPPORTED_OPTIONS.contains(option) || delegate.supportsOption(option);
}
@Override
protected boolean readClosed() {
return super.readClosed();
}
@Override
protected boolean writeClosed() {
return super.writeClosed();
}
protected void closeAction() {
sslConduit.close();
}
private final class HandshakeCallback implements Runnable {
@Override
public void run() {
final ChannelListener<? super SslConnection> listener = handshakeSetter.get();
if (listener == null) {
return;
}
ChannelListeners.<SslConnection>invokeChannelListener(UndertowSslConnection.this, listener);
}
}
}
| rhusar/undertow | core/src/main/java/io/undertow/protocols/ssl/UndertowSslConnection.java | Java | apache-2.0 | 5,435 |
/*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.bpmn.client.commands.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.ext.wires.bpmn.client.commands.Command;
import org.uberfire.ext.wires.bpmn.client.commands.ResultType;
import org.uberfire.ext.wires.bpmn.client.commands.Results;
import org.uberfire.ext.wires.bpmn.client.rules.RuleManager;
/**
* A batch of Commands to be executed as an atomic unit
*/
public class BatchCommand implements Command {
private List<Command> commands;
public BatchCommand( final List<Command> commands ) {
this.commands = PortablePreconditions.checkNotNull( "commands",
commands );
}
public BatchCommand( final Command... commands ) {
this.commands = Arrays.asList( PortablePreconditions.checkNotNull( "commands",
commands ) );
}
@Override
public Results apply( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.apply( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command undo : appliedCommands ) {
undo.undo( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
@Override
public Results undo( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.undo( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command cmd : appliedCommands ) {
cmd.apply( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/commands/impl/BatchCommand.java | Java | apache-2.0 | 2,980 |
/*
* Copyright 2010 Henry Coles
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.pitest.mutationtest;
public class MutableIncrement {
public static int increment() {
int i = 42;
i++;
return i;
}
}
| jacksonpradolima/pitest | pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java | Java | apache-2.0 | 735 |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.testdata;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.stream.Collectors;
public interface InterfaceWithLambda {
String ZERO = String.valueOf(0);
List<String> DIGITS =
ImmutableList.of(0, 1)
.stream()
.map(i -> i == 0 ? ZERO : String.valueOf(i))
.collect(Collectors.toList());
}
| aehlig/bazel | src/test/java/com/google/devtools/build/android/desugar/testdata/InterfaceWithLambda.java | Java | apache-2.0 | 1,029 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.wire;
/**
* Class to represent {@link FileSystemCommand} options.
*/
public final class FileSystemCommandOptions {
private PersistCommandOptions mPersistCommandOptions;
/**
* Creates a new instance of {@link FileSystemCommandOptions}.
*/
public FileSystemCommandOptions() {}
/**
* @return the persist options
*/
public PersistCommandOptions getPersistOptions() {
return mPersistCommandOptions;
}
/**
* Set the persist options.
*
* @param persistCommandOptions the persist options
*/
public void setPersistOptions(PersistCommandOptions persistCommandOptions) {
mPersistCommandOptions = persistCommandOptions;
}
}
| wwjiang007/alluxio | core/common/src/main/java/alluxio/wire/FileSystemCommandOptions.java | Java | apache-2.0 | 1,198 |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.rules.Tool;
import com.google.common.collect.ImmutableList;
import java.util.Optional;
public class ClangCompiler extends DefaultCompiler {
public ClangCompiler(Tool tool) {
super(tool);
}
@Override
public Optional<ImmutableList<String>> debugCompilationDirFlags(String debugCompilationDir) {
return Optional.of(
ImmutableList.of("-Xclang", "-fdebug-compilation-dir", "-Xclang", debugCompilationDir));
}
@Override
public Optional<ImmutableList<String>> getFlagsForColorDiagnostics() {
return Optional.of(ImmutableList.of("-fcolor-diagnostics"));
}
@Override
public boolean isArgFileSupported() {
return true;
}
}
| sdwilsh/buck | src/com/facebook/buck/cxx/ClangCompiler.java | Java | apache-2.0 | 1,330 |
/*
Copyright 2013-2014, JUMA Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.bcsphere.bluetooth;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import org.bcsphere.bluetooth.tools.BluetoothDetection;
import org.bcsphere.bluetooth.tools.Tools;
public class BCBluetooth extends CordovaPlugin {
public Context myContext = null;
private SharedPreferences sp;
private boolean isSetContext = true;
private IBluetooth bluetoothAPI = null;
private String versionOfAPI;
private CallbackContext newadvpacketContext;
private CallbackContext disconnectContext;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final String TAG = "BCBluetooth";
//classical interface relative data structure
public HashMap<String, BluetoothSerialService> classicalServices = new HashMap<String, BluetoothSerialService>();
//when the accept services construct a connection , the service will remove from this map & append into classicalServices map for read/write interface call
public HashMap<String, BluetoothSerialService> acceptServices = new HashMap<String, BluetoothSerialService>();
public BCBluetooth() {
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
myContext = this.webView.getContext();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
myContext.registerReceiver(receiver, intentFilter);
sp = myContext.getSharedPreferences("VERSION_OF_API", 1);
BluetoothDetection.detectionBluetoothAPI(myContext);
try {
if ((versionOfAPI = sp.getString("API", "no_google"))
.equals("google")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothG43plus")
.newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_samsung"))
.equals("samsung")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothSam42").newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_htc"))
.equals("htc")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothHTC41").newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean execute(final String action, final JSONArray json,
final CallbackContext callbackContext) throws JSONException {
try {
if(bluetoothAPI != null){
if (isSetContext) {
bluetoothAPI.setContext(myContext);
isSetContext = false;
}
if (action.equals("getCharacteristics")) {
bluetoothAPI.getCharacteristics(json, callbackContext);
} else if (action.equals("getDescriptors")) {
bluetoothAPI.getDescriptors(json, callbackContext);
} else if (action.equals("removeServices")) {
bluetoothAPI.removeServices(json, callbackContext);
}
if (action.equals("stopScan")) {
bluetoothAPI.stopScan(json, callbackContext);
} else if (action.equals("getConnectedDevices")) {
bluetoothAPI.getConnectedDevices(json, callbackContext);
}
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
if (action.equals("startScan")) {
bluetoothAPI.startScan(json, callbackContext);
} else if (action.equals("connect")) {
bluetoothAPI.connect(json, callbackContext);
} else if (action.equals("disconnect")) {
bluetoothAPI.disconnect(json, callbackContext);
} else if (action.equals("getServices")) {
bluetoothAPI.getServices(json, callbackContext);
} else if (action.equals("writeValue")) {
bluetoothAPI.writeValue(json, callbackContext);
} else if (action.equals("readValue")) {
bluetoothAPI.readValue(json, callbackContext);
} else if (action.equals("setNotification")) {
bluetoothAPI.setNotification(json, callbackContext);
} else if (action.equals("getDeviceAllData")) {
bluetoothAPI.getDeviceAllData(json, callbackContext);
} else if (action.equals("addServices")) {
bluetoothAPI.addServices(json, callbackContext);
} else if (action.equals("getRSSI")) {
bluetoothAPI.getRSSI(json, callbackContext);
}
}
});
}
if (action.equals("addEventListener")) {
String eventName = Tools.getData(json, Tools.EVENT_NAME);
if (eventName.equals("newadvpacket") ) {
newadvpacketContext = callbackContext;
}else if(eventName.equals("disconnect")){
disconnectContext = callbackContext;
}
if(bluetoothAPI != null){
bluetoothAPI.addEventListener(json, callbackContext);
}
return true;
}
if (action.equals("getEnvironment")) {
JSONObject jo = new JSONObject();
Tools.addProperty(jo, "appID", "com.test.yourappid");
Tools.addProperty(jo, "deviceAddress", "N/A");
Tools.addProperty(jo, "api", versionOfAPI);
callbackContext.success(jo);
return true;
}
if (action.equals("openBluetooth")) {
if(!bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("closeBluetooth")) {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("getBluetoothState")) {
Log.i(TAG, "getBluetoothState");
JSONObject obj = new JSONObject();
if (bluetoothAdapter.isEnabled()) {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE);
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE);
callbackContext.success(obj);
}
return true;
}
if(action.equals("startClassicalScan")){
Log.i(TAG,"startClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.startDiscovery()){
callbackContext.success();
}else{
callbackContext.error("start classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("stopClassicalScan")){
Log.i(TAG,"stopClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.cancelDiscovery()){
callbackContext.success();
}else{
callbackContext.error("stop classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("rfcommConnect")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
String securestr = Tools.getData(json, Tools.SECURE);
String uuidstr = Tools.getData(json, Tools.UUID);
boolean secure = false;
if(securestr != null && securestr.equals("true")){
secure = true;
}
Log.i(TAG,"connect to "+deviceAddress);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
BluetoothSerialService classicalService = classicalServices.get(deviceAddress);
if(device != null && classicalService == null){
classicalService = new BluetoothSerialService();
classicalService.disconnectCallback = disconnectContext;
classicalServices.put(deviceAddress, classicalService);
}
if (device != null) {
classicalService.connectCallback = callbackContext;
classicalService.connect(device,uuidstr,secure);
} else {
callbackContext.error("Could not connect to " + deviceAddress);
}
}
if (action.equals("rfcommDisconnect")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.connectCallback = null;
service.stop();
classicalServices.remove(deviceAddress);
callbackContext.success();
}else{
callbackContext.error("Could not disconnect to " + deviceAddress);
}
}
if(action.equals("rfcommListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
String securestr = Tools.getData(json, Tools.SECURE);
boolean secure = false;
if(securestr.equals("true")){
secure = true;
}
BluetoothSerialService service = new BluetoothSerialService();
service.listen(name, uuidstr, secure, this);
acceptServices.put(name+uuidstr, service);
}
if(action.equals("rfcommUnListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
BluetoothSerialService service = acceptServices.get(name+uuidstr);
if(service != null){
service.stop();
}
}
if(action.equals("rfcommWrite")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
String data = Tools.getData(json, Tools.WRITE_VALUE);
service.write(Tools.decodeBase64(data));
callbackContext.success();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommRead")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
byte[] data = new byte[2048];
byte[] predata = service.buffer.array();
for(int i = 0;i < service.bufferSize;i++){
data[i] = predata[i];
}
JSONObject obj = new JSONObject();
//Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress);
Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data));
Tools.addProperty(obj, Tools.DATE, Tools.getDateString());
callbackContext.success(obj);
service.bufferSize = 0;
service.buffer.clear();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommSubscribe")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = callbackContext;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("rfcommUnsubscribe")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = null;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("getPairedDevices")) {
try {
Log.i(TAG, "getPairedDevices");
JSONArray ary = new JSONArray();
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
BluetoothDevice device = (BluetoothDevice) it.next();
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
ary.put(obj);
}
callbackContext.success(ary);
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch (java.lang.Error e) {
Tools.sendErrorMsg(callbackContext);
}
} else if (action.equals("createPair")) {
Log.i(TAG, "createPair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.creatBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
} else if (action.equals("removePair")) {
Log.i(TAG, "removePair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.removeBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
}
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch(Error e){
Tools.sendErrorMsg(callbackContext);
}
return true;
}
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 11) {
JSONObject joOpen = new JSONObject();
try {
joOpen.put("state", "open");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothopen')");
} else if (intent.getIntExtra(
BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 13) {
JSONObject joClose = new JSONObject();
try {
joClose.put("state", "close");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothclose')");
}else if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("new classical bluetooth device found!"+device.getAddress());
// Add the name and address to an array adapter to show in a ListView
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
Tools.addProperty(obj, Tools.IS_CONNECTED, Tools.IS_FALSE);
Tools.addProperty(obj, Tools.TYPE, "Classical");
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK , obj);
pluginResult.setKeepCallback(true);
newadvpacketContext.sendPluginResult(pluginResult);
}
}
};
}
| bcsphere/bcexplorer | plugins/org/src/android/org/bcsphere/bluetooth/BCBluetooth.java | Java | apache-2.0 | 15,604 |
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.modelcompiler;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.drools.modelcompiler.domain.Address;
import org.drools.modelcompiler.domain.Employee;
import org.drools.modelcompiler.domain.Person;
import org.junit.Test;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieSession;
import static org.drools.modelcompiler.domain.Employee.createEmployee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OrTest extends BaseModelTest {
public OrTest( RUN_TYPE testRunType ) {
super( testRunType );
}
@Test
public void testOr() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age > $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Mario" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWhenStringFirst() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"rule R when\n" +
" $s : String(this == \"Go\")\n" +
" ( Person(name == \"Mark\") or \n" +
" (\n" +
" Person(name == \"Mario\") and\n" +
" Address(city == \"London\") ) )\n" +
"then\n" +
" System.out.println(\"Found: \" + $s.getClass());\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Go" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Mario", 100 ) );
ksession.insert( new Address( "London" ) );
assertEquals(2, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndex() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndexOffset() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $e : Person(name == \"Edson\")\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrConditional() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, address.city == 'Big City' )\n" +
" or " +
" Employee( $address: address, address.city == 'Small City' )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrConstraint() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, ( address.city == 'Big City' || address.city == 'Small City' ) )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrWithDuplicatedVariables() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R1 when\n" +
" Person( $name: name == \"Mark\", $age: age ) or\n" +
" Person( $name: name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $name + \" is \" + $age);\n" +
"end\n" +
"rule R2 when\n" +
" $p: Person( name == \"Mark\", $age: age ) or\n" +
" $p: Person( name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $p + \" has \" + $age + \" years\");\n" +
"end\n";
KieSession ksession = getKieSession( str );
List<String> results = new ArrayList<>();
ksession.setGlobal("list", results);
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
ksession.fireAllRules();
assertEquals(4, results.size());
assertTrue(results.contains("Mark is 37"));
assertTrue(results.contains("Mark has 37 years"));
assertTrue(results.contains("Mario is 40"));
assertTrue(results.contains("Mario has 40 years"));
}
@Test
public void generateErrorForEveryFieldInRHSNotDefinedInLHS() {
// JBRULES-3390
final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" +
"declare B\n" +
" field : int\n" +
"end\n" +
"declare C\n" +
" field : int\n" +
"end\n" +
"rule R when\n" +
"( " +
" ( B( $bField : field ) or C( $cField : field ) ) " +
")\n" +
"then\n" +
" System.out.println($bField);\n" +
"end\n";
Results results = getCompilationResults(drl1);
assertFalse(results.getMessages().isEmpty());
}
private Results getCompilationResults( String drl ) {
return createKieBuilder( drl ).getResults();
}
}
| jomarko/drools | drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/OrTest.java | Java | apache-2.0 | 9,484 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.importing;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.utils.Path;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import java.io.File;
public class MavenRootModelAdapter implements MavenRootModelAdapterInterface {
private final MavenRootModelAdapterInterface myDelegate;
public MavenRootModelAdapter(MavenRootModelAdapterInterface delegate) {myDelegate = delegate;}
@Override
public void init(boolean isNewlyCreatedModule) {
myDelegate.init(isNewlyCreatedModule);
}
@Override
public ModifiableRootModel getRootModel() {
return myDelegate.getRootModel();
}
@Override
public String @NotNull [] getSourceRootUrls(boolean includingTests) {
return myDelegate.getSourceRootUrls(includingTests);
}
@Override
public Module getModule() {
return myDelegate.getModule();
}
@Override
public void clearSourceFolders() {
myDelegate.clearSourceFolders();
}
@Override
public <P extends JpsElement> void addSourceFolder(String path,
JpsModuleSourceRootType<P> rootType) {
myDelegate.addSourceFolder(path, rootType);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType, boolean ifNotEmpty) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType, ifNotEmpty);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType);
}
@Override
public boolean hasRegisteredSourceSubfolder(@NotNull File f) {
return myDelegate.hasRegisteredSourceSubfolder(f);
}
@Override
@Nullable
public SourceFolder getSourceFolder(File folder) {
return myDelegate.getSourceFolder(folder);
}
@Override
public boolean isAlreadyExcluded(File f) {
return myDelegate.isAlreadyExcluded(f);
}
@Override
public void addExcludedFolder(String path) {
myDelegate.addExcludedFolder(path);
}
@Override
public void unregisterAll(String path, boolean under, boolean unregisterSources) {
myDelegate.unregisterAll(path, under, unregisterSources);
}
@Override
public boolean hasCollision(String sourceRootPath) {
return myDelegate.hasCollision(sourceRootPath);
}
@Override
public void useModuleOutput(String production, String test) {
myDelegate.useModuleOutput(production, test);
}
@Override
public Path toPath(String path) {
return myDelegate.toPath(path);
}
@Override
public void addModuleDependency(@NotNull String moduleName, @NotNull DependencyScope scope, boolean testJar) {
myDelegate.addModuleDependency(moduleName, scope, testJar);
}
@Override
@Nullable
public Module findModuleByName(String moduleName) {
return myDelegate.findModuleByName(moduleName);
}
@Override
public void addSystemDependency(MavenArtifact artifact, DependencyScope scope) {
myDelegate.addSystemDependency(artifact, scope);
}
@Override
public LibraryOrderEntry addLibraryDependency(MavenArtifact artifact,
DependencyScope scope,
IdeModifiableModelsProvider provider,
MavenProject project) {
return myDelegate.addLibraryDependency(artifact, scope, provider, project);
}
@Override
public Library findLibrary(@NotNull MavenArtifact artifact) {
return myDelegate.findLibrary(artifact);
}
@Override
public void setLanguageLevel(LanguageLevel level) {
myDelegate.setLanguageLevel(level);
}
static boolean isChangedByUser(Library library) {
String[] classRoots = library.getUrls(
OrderRootType.CLASSES);
if (classRoots.length != 1) return true;
String classes = classRoots[0];
if (!classes.endsWith("!/")) return true;
int dotPos = classes.lastIndexOf("/", classes.length() - 2 /* trim ending !/ */);
if (dotPos == -1) return true;
String pathToJar = classes.substring(0, dotPos);
if (MavenRootModelAdapter
.hasUserPaths(OrderRootType.SOURCES, library, pathToJar)) {
return true;
}
if (MavenRootModelAdapter
.hasUserPaths(
JavadocOrderRootType
.getInstance(), library, pathToJar)) {
return true;
}
return false;
}
private static boolean hasUserPaths(OrderRootType rootType, Library library, String pathToJar) {
String[] sources = library.getUrls(rootType);
for (String each : sources) {
if (!FileUtil.startsWith(each, pathToJar)) return true;
}
return false;
}
public static boolean isMavenLibrary(@Nullable Library library) {
return library != null && MavenArtifact.isMavenLibrary(library.getName());
}
public static ProjectModelExternalSource getMavenExternalSource() {
return ExternalProjectSystemRegistry.getInstance().getSourceById(ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID);
}
@Nullable
public static OrderEntry findLibraryEntry(@NotNull Module m, @NotNull MavenArtifact artifact) {
String name = artifact.getLibraryName();
for (OrderEntry each : ModuleRootManager.getInstance(m).getOrderEntries()) {
if (each instanceof LibraryOrderEntry && name.equals(((LibraryOrderEntry)each).getLibraryName())) {
return each;
}
}
return null;
}
@Nullable
public static MavenArtifact findArtifact(@NotNull MavenProject project, @Nullable Library library) {
if (library == null) return null;
String name = library.getName();
if (!MavenArtifact.isMavenLibrary(name)) return null;
for (MavenArtifact each : project.getDependencies()) {
if (each.getLibraryName().equals(name)) return each;
}
return null;
}
}
| GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java | Java | apache-2.0 | 6,985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.